MVVM 中的简单事件处理 [英] Simple Event Handling in MVVM
问题描述
只是想知道人们对如何最好地从 View 上的控件处理 ViewModel 中的事件有什么想法......以尽可能最轻量的方式.
Just wondering what people had for ideas on how best to handle events in a ViewModel from controls on a View ... in the most lightweight way possible.
示例:
<MediaElement
MediaOpened={Binding SomeEventHandler} />
在这种情况下,我们希望在 ViewModel 中处理 MediaOpened 事件.如果没有像 Prism 这样的框架,如何将它绑定到 ViewModel?
In this case we want to handle the MediaOpened event in a ViewModel. Without a framework like Prism, how would one bind this to a ViewModel?
推荐答案
Commanding - 你的SomeEventHandler"需要是一个实现 ICommand
的类......网上有很多文献......
Commanding - your 'SomeEventHandler' needs to be a class that implements ICommand
... there's a heap of literature available online...
另外 - 我会考虑获得一个免费的、轻量级的迷你"MVVM 框架,例如 MvvmFoundation,它为这样的目的提供了 RelayCommand(没有学习 PRISM 的复杂性/开销)
Also - I would consider getting a free, lightweight 'mini' MVVM framework, such as MvvmFoundation, which provides the RelayCommand for just such a purpose (without the complexity/overhead of learning PRISM)
看看 this 用于将命令附加到任何事件的博客......正如我所提到的,它非常强大,但我想如果这是你想要的,与类似于附加一个老式事件,并在后面的代码中使用超薄事件处理程序,它只是调用 ViewModel 上的某些方法,例如:
Have a look at this blog for attaching command to any event... It is incredibly powerful, as I mentioned, but I guess you do need to make a judgement call if this is what you want, compared with something like attaching an old-fashioned event, and using a super-slim event handler in your code behind that simply invokes some method on your ViewModel, something like:
public void SomeEventHandler(object sender, SomeEventArgs e)
{
MyViewModel vm = (MyViewModel)this.DataContext;
vm.HandleLoadEvent( );
}
务实与最佳实践......我会留给你;)
pragmatic vs Best-practise... I'll leave it with you ;)
这篇关于MVVM 中的简单事件处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!