从 View 到 ViewModel 的 WPF 事件绑定? [英] WPF event binding from View to ViewModel?

查看:24
本文介绍了从 View 到 ViewModel 的 WPF 事件绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the best way to bind a WPF event in the View to the ViewModel?

我的视图中有一个放置事件,但我想将其替换为 ViewModel 到期绑定.

I have a drop event in my View but I want to replace it to the ViewModel due binding.

找到了几个解决方案,但没有一个达到我的预期.

Found several solutions but none of them did what I expected.

查看代码:

    <TextBox 
    AllowDrop="True" 
    PreviewDrop="email_Drop" />

推荐答案

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

One way to handle events in MVVM and XAML is to use the Blend Interactivity features. This namespace contains the InvokeCommandAction and the CallMethodAction classes.

InvokeCommandAction 可让您将任何事件绑定到视图模型命令,而 CallMethodAction 可让您将任何事件绑定到视图模型方法.

InvokeCommandAction lets you bind any event to a view-model command while CallMethodAction lets you bind any event to a view-model method.

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

For example if you want to bind the DoubleClick event of a Button to a view-model command you would do like this:

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

All you need to reference it in your projects is to install Expression Blend or the Expression Blend SDK.

这篇关于从 View 到 ViewModel 的 WPF 事件绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆