如何将WPF视图中的事件绑定到ViewModel?
我在我的View中有一个拖放事件,但由于要绑定,我想将它迁移到ViewModel中。
找到了几个解决方案,但都没有达到我预期的效果。
View代码:
<TextBox
AllowDrop="True"
PreviewDrop="email_Drop" />
如何将WPF视图中的事件绑定到ViewModel?
我在我的View中有一个拖放事件,但由于要绑定,我想将它迁移到ViewModel中。
找到了几个解决方案,但都没有达到我预期的效果。
View代码:
<TextBox
AllowDrop="True"
PreviewDrop="email_Drop" />
MVVM和XAML处理事件的一种方法是使用Blend交互功能。该命名空间包含InvokeCommandAction和CallMethodAction类。
InvokeCommandAction可将任何事件绑定到视图模型命令,而CallMethodAction可将任何事件绑定到视图模型方法。
例如,如果您想将按钮的DoubleClick事件绑定到视图模型命令,可以这样做:
<Button>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<i:InvokeCommandAction Command="{Binding Path=DoSomethingCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
并声明这个命名空间:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
您只需要安装Expression Blend或Expression Blend SDK,即可在项目中引用它。
一种方法是将该事件转换为命令,并将其绑定到Presenter命令,即通过定义事件行为。
<Button MouseDoubleClick="{eb:EventBinding Command=DoSomethingCommand}">
</Button>
命令
{eb:EventBinding}(简单的命名模式,用于查找命令)
{eb:EventBinding Command = CommandName}
CommandParameter (命令参数)
$e(EventAgrs)
$this或$this.Property
字符串
public partial class ParentView : ContentPage
{
public ParentView()
{
InitializeComponent();
}
private void LanguagePicker_SelectedIndexChanged(object sender, System.EventArgs e)
{
var parentViewModel = (ParentViewModel)this.BindingContext;
parentViewModel.SelectedLanguageChanged(sender,e);
}
}