WPF 事件绑定到 ViewModel(对于非命令类) [英] WPF Event Binding to ViewModel (for non-Command classes)

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

问题描述

我正在开发应用程序的第二个版本,作为重写的一部分,我必须转向 MVVM 架构.我面临着将绝对所有代码都放在视图模型类中的压力——在代码隐藏文件中使用 c# 是不受欢迎的.(我知道,我知道……我知道代码隐藏并不是一件坏事,但这次不是我的要求).

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

对于实现命令接口的对象,这很容易.我已经能够找到大量关于如何将这些对象的 Command 绑定到视图模型中的 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>

我想知道如何将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 Light 有一个很棒的 EventToCommand 行为将任何事件映射到 ViewModel 上的 ICommand.使用 ICommand 的优点是您仍然可以使用 DataBinding,因为 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 事件绑定到 ViewModel(对于非命令类)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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