WPF事件绑定到视图模型(非指挥类) [英] WPF Event Binding to ViewModel (for non-Command classes)

查看:149
本文介绍了WPF事件绑定到视图模型(非指挥类)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个应用程序的第二版本,并且作为重写的第一部分必须移动到一个MVVM架构。我得到pressure把绝对code的每一位在视图模型类 - 具有隐藏文件中的code是不可取的C#。 (我知道,我知道......我明白,code的背后,是不是一件坏事,但它不是我的电话这个时候)。

I'm working an the second version of an application, and as part of the rewrite I have to move to an MVVM architecture. I'm getting pressure to put absolutely every bit of code in the view model class--having c# in the code behind file is frowned upon. (I know, I know...I understand that code behind isn't a bad thing, but it isn't my call this time).

对于实现该命令接口的对象,这很容易。我已经能够找到如何对这些对象的命令绑定到一个ICommand的视图模型一吨的信息。问题是对于不具有这样的接口,对象例如

For objects which implement the command interface, it's easy. I've been able to find a ton of information on how to bind the Command of these objects to an ICommand in the view model. The problem is for objects which don't have this interface, e.g.

<ListBox
   x:Name="myListBox"
   MouseDoubleClick="myCallbackFunction">

<!-- ... -->

</ListBox>

我想知道如何MouseDoubleClick事件绑定的列表框中myCallbackFunction,这是在视图模型实现的。这甚至可能?

I want to know how to bind the MouseDoubleClick event for the Listbox to myCallbackFunction, which is implemented in the view model. Is this even possible?

谢谢!

推荐答案

这是不能直接成为可能。它可以通过附加属性或行为来完成,但它仍然是一个有点棘手找到并调用适当的方法(这可以通过反射来实现很容易)。

This isn't directly possible. It could be done via an Attached Property or Behavior, though it would still be a little tricky to find and invoke the appropriate method (this could be done via Reflection fairly easily).

话虽这么说,这通常通过 ICommand的处理 - 例如,MVVM光有一个伟大的<一个href=\"http://geekswithblogs.net/lbugnion/archive/2009/11/05/mvvm-light-toolkit-v3-alpha-2-eventtocommand-behavior.aspx\">EventToCommand行为映射任何事件的视图模型一个ICommand。使用的ICommand的好处是,你仍然可以使用数据绑定,因为ICommand的公开为一个属性。

That being said, this is typically handled via ICommand - For example, MVVM Light has a great EventToCommand behavior to map any event to an ICommand on the ViewModel. The advantage of using ICommand is that you can still use DataBinding, since the ICommand is exposed as a property.

这篇关于WPF事件绑定到视图模型(非指挥类)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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