wpf MouseDown、PreviewMouseDown 等...以及 MVVM 中的 COMMAND 绑定

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12270134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 05:12:52  来源:igfitidea点击:

MouseDown, PreviewMouseDown, etc... and COMMAND Binding in MVVM

wpfmvvmbindingcommandmousedown

提问by tronious

I'm trying to understand this concept and it's eluding me.

我正在尝试理解这个概念,但它让我望而却步。

What is the general concept behind this? I know it's possible, but I'm not totally following how to do this based on my research/own test projects.

这背后的一般概念是什么?我知道这是可能的,但我并没有完全按照我的研究/自己的测试项目来做到这一点。

I want to avoid code behind at all costs in my View. I want to decouple events such as "PreviewMouseDown" from the View and have them trigger a Command in the ViewModel.

我想不惜一切代价避免在我的视图中隐藏代码。我想从视图中分离诸如“PreviewMouseDown”之类的事件,并让它们触发 ViewModel 中的命令。

Can anyone give me some basic guidance on how to accomplish this?

谁能给我一些关于如何实现这一点的基本指导?

Summary:

概括:

View (PreviewMouseDown) -> Calls Command in ViewModel (MyPreviewMouseDownCommand)

视图 (PreviewMouseDown) -> 在 ViewModel 中调用命令 (MyPreviewMouseDownCommand)

Thank you

谢谢

采纳答案by Erre Efe

It's all about Commandingand Binding. But I'll encourage you to better use a framework that provides you the plumbing. If you want View first strategy you can you go with MVVM Light as Reedsuggested. But, if you want ViewModel first approach (which I personallyfound to be more simple to understand) then I'll suggest you to use Caliburn Micro.

这都是关于CommandingBinding 的。但我会鼓励您更好地使用为您提供管道的框架。如果您想要查看优先策略,您可以按照Reed 的建议使用 MVVM Light 。但是,如果您想要 ViewModel 第一种方法(我个人认为它更易于理解),那么我建议您使用Caliburn Micro

Anyway, you'll end up using Event to Command or the Interactivity Library (from the Blend SDK) if you want to go code-behind clean.

无论如何,如果您想要清理代码隐藏,您最终将使用 Event to Command 或交互性库(来自 Blend SDK)。

回答by Kevin DiTraglia

At risk of being downvoted I don't think this is the worst thing in the world

冒着被否决的风险,我不认为这是世界上最糟糕的事情

public void PreviewMouseDown(Object sender, RoutedEventArgs e)
{
    var viewModel= (MyViewModel)DataContext;
    if (viewModel.MyCommand.CanExecute(null))
        viewModel.MyCommand.Execute(null);
}

回答by Reed Copsey

This is typically handled via some form of Attached Propertyor (Blend) Behavior.

这通常通过某种形式的附加属性(混合)行为来处理

For example, MVVM Light includes an EventToCommand Behaviorwhich allows you to route any event to an ICommandin XAML, with no code behind added.

例如,MVVM Light 包括一个EventToCommand Behavior,它允许您将任何事件路由到ICommandXAML 中,而无需添加任何代码。