本次所分享的是Interaction.Triggers,Interaction.Triggers到底是什么呢?有什么用?Interaction.Triggers其实是WPF中的一种触发器,其作用是交互,所以它又叫交互触发器。
其实一般情况下用到这种特殊的交互触发器,在不太需要的情况下是不会去使用。那究竟在什么时候使用呢?当WPFmvvm模式下某个控件或其他:好比如Button的点击事件,在mvvm模式下Button的点击事件有时候是不可以直接使用ICommand的,这时候这中特殊手段就对mvvm模式非常有用,但是在使用Interaction.Triggers之前我们的项目还需要添加一个引用:
System.Windows.Interactivity.dll
接下来直接进入步骤:
以Button举个例子:
首先引用System.Window.Interactivity.dll
在您的xaml(UserControl或者是Window)添加这个特性
<UserControl x:Class="……………"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
Height="500" Width="800">
或者:
<UserControl x:Class="Afterall_MVVM.Views.TPIstorageManagement"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
Height="500" Width="800">
接下来就在需要的地方,比如某个不小心的Button
<Button Height="18" Width="18" Margin="5 0 0 0">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:InvokeCommandAction Command="{Binding tvSupplierCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
这里EventName中是放想要执行的事件,好比如想要个双击事件MouseDoubleClick,也可以是Click。
然后再ViewModel中创建pulic方法
- 构造函数
public void TPIstorageInit()
{
//打开供应商
tvSupplierCommand = new RelayCommand(tvSupplier);
}
- 命令
public RelayCommand tvSupplierCommand { get; set; }
- public
//打开选项数据表格
public void tvSupplier()
{
SupplierAddWindow my = new SupplierAddWindow();
var myViewModel = (my.DataContext as SupplierAddViewModes);
my.ShowDialog();
}
附图: