[英]WPF event binding from View to ViewModel?
將 View 中的 WPF 事件綁定到 ViewModel 的最佳方法是什么?
我的視圖中有一個放置事件,但我想將其替換為 ViewModel 到期綁定。
找到了幾個解決方案,但沒有一個達到我的預期。
查看代碼:
<TextBox
AllowDrop="True"
PreviewDrop="email_Drop" />
在 MVVM 和 XAML 中處理事件的一種方法是使用混合交互功能。 此命名空間包含 InvokeCommandAction 和 CallMethodAction 類。
InvokeCommandAction 允許您將任何事件綁定到視圖模型命令,而 CallMethodAction 允許您將任何事件綁定到視圖模型方法。
例如,如果您想將 Button 的 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。
一種方法是將該事件轉換為命令,然后將其綁定到演示者命令,即通過定義事件行為。
<Button MouseDoubleClick="{eb:EventBinding Command=DoSomethingCommand}">
</Button>
命令
{eb:EventBinding}(查找命令的簡單命名模式)
{eb:EventBinding 命令=命令名稱}
命令參數
$e (EventAgrs)
$this 或 $this.Property
細繩
我從 bindingcontext 獲取 viewmodel 並從那里激活我的 viewmodel 方法
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.