为了符合MVVM框架设计,所以需要将页面控件的事件绑定到VM中进行处理.
同时,绑定的事件传值可以不再受限于原来的后端页面逻辑,可以传任何你需要处理的页面参数、控件参数和VM等
举例说明:
<RichTextBox x:Name="rtBox">
<i:Interaction.Triggers>
<i:EventTrigger EventName="DataLoaded">
<i:InvokeCommandAction Command="{Binding DataLoadedCommand}" CommandParameter="{Binding}"/>
</i:EventTrigger>
<i:EventTrigger EventName="GotFocus">
<i:InvokeCommandAction Command="{Binding GotFocusCommand}" CommandParameter="{Binding ElementName=rtBox}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</RichTextBox>
上面分别绑定了两个事件, CommandParameter中"{Binding}"意为绑定了当前的VM,即"MyVM".
第二个命令"{Binding ElementName=textBox}"指定了一个元素textBox,因此在VM中要用泛型参数传值,VM中命令如下:
public class MyVM : ShapeBaseVM
{
public static MyVM Instance;
public MyVM()
{
Instance = this;
}
private RelayCommand dataLoaded;
public RelayCommand DataLoadedCommand
{
get
{
return dataLoaded ?? (dataLoaded = new RelayCommand(() =>
{
var vm = Shape.TextRange;
if (vm.IsDispose)
{
throw new Exception("当前资源已释放且没有赋值新资源");
}
if (!vm.IsConvertDone)
{
vm.ConvertRtf();
}
RaisePropertyChanged("Rtf");
}));
}
}
private RelayCommand<RichTextBox> gotFocus;
public RelayCommand<RichTextBox> GotFocusCommand
{
get
{
return gotFocus ?? (gotFocus = new RelayCommand<RichTextBox>(sender =>
{
Console.WriteLine("gotFocus:" + sender.Id);
}));
}
}
}
这样就可以把后台逻辑转移到VM中处理了