WPF:如何在没有代码隐藏代码的情况下将事件从 ViewModel 发送到 View? [英] WPF: how to signal an event from ViewModel to View without code in codebehind?

查看:17
本文介绍了WPF:如何在没有代码隐藏代码的情况下将事件从 ViewModel 发送到 View?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很简单的(我希望:))问题:

在 MVVM 中,View 通常会监听 ViewModel 属性的变化.但是,有时我想监听事件,例如,当 VM 发出信号时,View 可以启动动画或关闭窗口.

通过带有 NotifyPropertyChanged 的​​ bool 属性(并且只有在它从 false 变为 true 时才启动动画)来实现它是可能的,但感觉就像一个黑客,我更喜欢公开事件,因为它在语义上是正确的.

另外,我想在没有代码隐藏的情况下完成它,因为执行 viewModel.myEvent += handler 意味着我必须手动取消注册事件以允许 View被垃圾回收 - WPF 视图已经能够弱"地侦听属性,我更喜欢仅在视图中进行声明式编程.

标准的强事件订阅也不好,因为我需要为一个View切换多个ViewModel(因为每次创建View都占用太多CPU时间).

谢谢你的想法(如果有标准的解决方案,一个到 msdn 的链接就足够了)!

解决方案

一些评论:

  • 您可以使用弱事件模式来确保即使视图仍然附加到视图模型的事件,它也可以被 GC 处理
  • 如果您已经为一个视图切换了多个 VM,那这不是附加/分离处理程序的理想位置吗?
  • 根据您的具体场景,您可以让 VM 公开一个状态属性,视图将其用作动画、过渡和其他视觉变化的触发器.可视化状态管理器这种事情.

I have quite simple (I hope :)) problem:

In MVVM, View usually listens on changes of ViewModel's properties. However, I would sometimes like to listen on event, so that, for example, View could start animation, or close window, when VM signals.

Doing it via bool property with NotifyPropertyChanged (and starting animation only when it changes from false to true) is possible, but it feels like a hack, I'd much prefer to expose event, as it is semantically correct.

Also, I'd like to do it without code in codebehind, as doing viewModel.myEvent += handler there would mean that I'd have manually unregister the event in order to allow View to be GC'd - WPF Views are already able to listen on properties 'weakly', and I'd much prefer to program only declaratively in View.

The standard strong event subscription is also bad, because I need to switch multiple ViewModels for one View (because creating View every time takes too much CPU time).

Thank you for ideas (if there is a standard solution, a link to msdn will suffice)!

解决方案

Some comments:

  • You can use the weak event pattern to ensure that the view can be GC'd even if it is still attached to the view model's event
  • If you're already switching multiple VMs in for the one view, wouldn't that be the ideal place to attach/detach the handler?
  • Depending on your exact scenario, you could just have the VM expose a state property which the view uses as a trigger for animations, transitions, and other visual changes. Visual state manager is great for this kind of thing.

这篇关于WPF:如何在没有代码隐藏代码的情况下将事件从 ViewModel 发送到 View?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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