wpf 在 MVVM 中处理 MouseLeftButtonDown

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14117377/
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 06:51:49  来源:igfitidea点击:

Handling MouseLeftButtonDown in MVVM

wpfxamlmvvmmouseeventcontroltemplate

提问by Kuntady Nithesh

My XAML is:

我的 XAML 是:

<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate>
            <Image Source="X.png" HorizontalAlignment="Left"
                                 Width="20" Height="20" 
                                 MouseLeftButtonDown="Image_MouseLeftButtonDown"/>
        </ControlTemplate>
    </Setter.Value>
</Setter>

Now I am following MVVM. I need to change the code to make it work with ViewModel. How can I handle MouseLeftButtonDownevent with ViewModel?

现在我正在关注 MVVM。我需要更改代码以使其与 ViewModel 一起使用。如何MouseLeftButtonDown使用 ViewModel处理事件?

回答by Blachshma

When working with MVVM: A trigger in the View (be it a MouseLeftDown, a MouseHover etc.) triggers a Commandin the ViewModel.
These commands perform some operation in the ViewModel, and if this command changes any data which is binded in the view, you can see the results in the view.

使用 MVVM 时:视图中的触发器(可以是 MouseLeftDown、MouseHover 等)会触发ViewModel 中的命令
这些命令在ViewModel中执行一些操作,如果这个命令改变了视图中绑定的任何数据,你可以在视图中看到结果。

Therefore don't ask "How can I handle MouseLeftButtonDown event with view model"rather decide what is it you want to do in the ViewModel (such as removing an item from a listbox, navigating to another view, refreshing the data etc...) and create a specific command for it.

因此,不要问“我如何使用视图模型处理 MouseLeftButtonDown 事件”,而是决定要在 ViewModel 中执行什么操作(例如从列表框中删除项目、导航到另一个视图、刷新数据等... ) 并为其创建特定命令。

The MouseLeftDown can triggerthat command... But what exactly is done should not be part of the view...

MouseLeftDown 可以触发该命令......但究竟做了什么不应该是视图的一部分......

Here is an exampleof catching a mouse event and running a command, using MVVM and only XAML.

这是一个使用 MVVM 和仅 XAML 捕获鼠标事件并运行命令的示例

回答by Mats Magnem

In my opinion, a left mouse button should not be handled by "MVVM" (handled by a binding). It has noting to do with the model, as it is relaetd to the UI experience.

在我看来,鼠标左键不应该由“MVVM”处理(由绑定处理)。它与模型无关,因为它与 UI 体验有关。

I would attach to the "old fashioned" MouseRightButtonDown event in my codebehind for that, and then fire the command or method in the view. Because the model does not need to know HOW the command was executed. Button clicks, mouse gestures and menues is UI-related.

为此,我会在我的代码隐藏中附加到“老式” MouseRightButtonDown 事件,然后在视图中触发命令或方​​法。因为模型不需要知道命令是如何执行的。按钮点击、鼠标手势和菜单与 UI 相关。

At least in my opinion :-)

至少在我看来 :-)