前言:MVVM开发模式下使用Command是非常方便的,但是很多控件没有Command,比如Text获得焦点、丢失焦点等,都是通过事件直接和View后台程序交互的。这时候如果还想在ViewModel实现Command功能,就需要借助点其他东西了。
明确一点,Microsoft.Expression.Interactions和System.Windows.Interactivity程序集在Blend工具中才有,不过,不知道从什么时间开始,这两个程序集弃用了,现在改成Microsoft.Xaml.Behaviors了。
一、System.Windows.Interactivity

可以看出来,依赖的Framwork最低版本是4.0,最高是4.8,而且只支持 .NETFramwork版本。
1.1 简介
如果目标框架是.NETFramwork的各种版本,比如4,4.8等版本,需要引入System.Windows.Interactivity.dll动态库,也可以通过NuGet进行下载,只不过,这个库,现在已经停止更新了,但是下载下来还是能用的。官方推荐的替代库是另一个库Microsoft.Xaml.Behaviors。

如果目标框架是.NET Core及以上的,也可以用,只是会有提示说使用.NETFramwork的其他版本对这个库进行还原。

1.2 使用
xaml中引用命名空间,这里有两种方式,可能有些版本是不可以的,笔者这里目标框架.NETFramwork4.8和.NET5进行测试,都是可以的。
- xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
-
- xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
- <TextBox Text="fengxiong" VerticalAlignment="Center">
- <i:Interaction.Triggers>
- <i:EventTrigger EventName="LostFocus">
- <i:InvokeCommandAction Command="{Binding OpenSerialPortCommand}"/>
- </i:EventTrigger>
- <i:EventTrigger EventName="GotFocus">
- <i:InvokeCommandAction Command="{Binding OpenSerialPortCommand}"/>
- </i:EventTrigger>
- </i:Interaction.Triggers>
- </TextBox>
这里Interaction下有两个选择,一个是Triggers,另一个是Behaviors,笔者网上搜了下相关文献,发现有些说是使用Behaviors,其实还是使用的Triggers。
二、Microsoft.Xaml.Behaviors
2.1 简介
笔者网上搜到的资料显示,第一个版本从2018年12月3号开始的。

而 System.Windows.Interactivity.WPF停更是2013年3月10号,而且只有一个版本。

官网上面System.Windows.Interactivity创建显示时间是2017年10月11

Microsoft.Xaml.Behaviors相关信息介绍如下。


2.2 使用
和System.Windows.Interactivity的使用方法是一样的,只是换了个命名空间。先下载后引用。

xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
- <TextBox Text="fengxiong" VerticalAlignment="Center">
- <i:Interaction.Triggers>
- <i:EventTrigger EventName="LostFocus">
- <i:InvokeCommandAction Command="{Binding OpenSerialPortCommand}"/>
- </i:EventTrigger>
- <i:EventTrigger EventName="GotFocus">
- <i:InvokeCommandAction Command="{Binding OpenSerialPortCommand}"/>
- </i:EventTrigger>
- </i:Interaction.Triggers>
- </TextBox>
三、引用文献
3.2 System.Windows.Interactivity 命名空间 | Microsoft Docs
3.4 WPF中System.Windows.Interactivity的使用_lpb914的博客-CSDN博客
3.5 NuGet Gallery | Microsoft.Xaml.Behaviors.Wpf 1.1.39
3.6 NuGet Gallery | System.Windows.Interactivity.WPF 2.0.20525