简体   繁体   English

WPF Mvvm 将鼠标按钮事件移动到命令

[英]WPF Mvvm move mouse button event to Command

I am starting to use MVVM but I'm finding difficult to replicate simple things that I do with events: I have a canvas and I want to get the position of the mouse click so I did a command and the xaml is this我开始使用 MVVM,但我发现很难复制我对事件所做的简单事情:我有一个 canvas,我想获得鼠标单击的 position,所以我执行了一个命令,xaml 就是这个

<Canvas x:Name="cnvLeft">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="PreviewMouseDown">
                <cmd:EventToCommand Command="{Binding CanvasClick}" 
                                    PassEventArgsToCommand="True"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
        
    </Canvas>

However it pass only the mouse arguments, which is not enough because i need the sender, how can i fix this?但是它只传递鼠标 arguments,这还不够,因为我需要发件人,我该如何解决这个问题?

As recommended already: register a common event handler for the mouse click event.正如已经推荐的那样:为鼠标单击事件注册一个公共事件处理程序。

MVVM is not concerned with code-behind. MVVM 不关心代码隐藏。 It's absolutely fine and even necessary to use code-behind.使用代码隐藏是绝对好的,甚至是必要的。
Code-behind files are a compiler feature ie language feature (partial classes).代码隐藏文件是一种编译器功能,即语言功能(部分类)。 They have nothing to do with application architecture.它们与应用程序架构无关。 MVVM does not care about compilers - no design pattern does. MVVM 不关心编译器——没有设计模式关心。

MVVM is also not concerned with commands (or data binding or any framework concept in general). MVVM 也不关心命令(或数据绑定或任何框架概念)。 Commanding is part of the framework's infrastructure and MVVM does not care about frameworks - no design pattern does.命令是框架基础设施的一部分,MVVM 不关心框架——没有设计模式关心。
MVVM does not mean to use commands. MVVM 并不意味着使用命令。 Events are usually just as good.事件通常一样好。 So don't force commands.所以不要强行命令。 Instead of using interaction behaviors to convert an input event to a command, simply handle the event directly (of course in the view).与其使用交互行为将输入事件转换为命令,不如直接处理事件(当然是在视图中)。

Controls must always be handled in the View of an MVVM application.控件必须始终在 MVVM 应用程序的视图中处理。 The code-behind file of a control is a partial class. It's part of the control and therefore part of the View.控件的代码隐藏文件是部分 class。它是控件的一部分,因此也是视图的一部分。

Implement the user input event handler in the hosting control's code-behind.在宿主控件的代码隐藏中实现用户输入事件处理程序。 Here you must implement the Canvas related logic (UI logic).这里必须实现Canvas相关逻辑(UI逻辑)。
If you want to encapsulate the logic, you can move it along with the Canvas to a new custom Control (or UserControl ).如果要封装逻辑,可以将其与Canvas一起移动到新的UserControl Control

MainWindow.xaml主窗口.xaml

<Window>
  <Canvas PreviewMouseDown="OnCanvasePreviewMouseDown" />
</Window>

MainWindow.xaml.cs MainWindow.xaml.cs

private void OnCanvasePreviewMouseDown(object sender, MouseButtonEventArgs e)
{
  var canvas = sender as Canvas;
  Point canvasClickPosition = e.GetPosition(canvas);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM