从View到ViewModel的WPF事件绑定?

jef*_*smi 22 c# wpf binding

什么是将View中的WPF事件绑定到ViewModel的最佳方法?

我在View中有一个drop事件,但我想将它替换为ViewModel到期绑定.找到了几个解决方案,但没有一个能达到我的预期.

查看代码:

    <TextBox 
    AllowDrop="True" 
    PreviewDrop="email_Drop" />
Run Code Online (Sandbox Code Playgroud)

Uco*_*dia 53

处理MVVM和XAML中的事件的一种方法是使用Blend Interactivity功能.此命名空间包含InvokeCommandAction和CallMethodAction类.

InvokeCommandAction允许您将任何事件绑定到view-model命令,而CallMethodAction允许您将任何事件绑定到视图模型方法.

例如,如果要将Button的DoubleClick事件绑定到视图模型命令,您可以这样做:

<Button>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseDoubleClick">
            <i:InvokeCommandAction Command="{Binding Path=DoSomethingCommand}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>
Run Code Online (Sandbox Code Playgroud)

并声明此命名空间:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
Run Code Online (Sandbox Code Playgroud)

您在项目中引用它所需的只是安装Expression Blend或Expression Blend SDK.


who*_*his 5

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

参见WPF事件绑定到ViewModel(用于非Command类)