繁体   English   中英

从 View 到 ViewModel 的 WPF 事件绑定?

[英]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。

一种方法是将该事件转换为命令,然后将其绑定到演示者命令,即通过定义事件行为。

看到这个, WPF Event Binding to ViewModel(对于非Command类)

<Button MouseDoubleClick="{eb:EventBinding Command=DoSomethingCommand}">

</Button>

命令

{eb:EventBinding}(查找命令的简单命名模式)

{eb:EventBinding 命令=命令名称}

命令参数

$e (EventAgrs)

$this 或 $this.Property

细绳

https://github.com/JonghoL/EventBindingMarkup

我从 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM