简体   繁体   中英

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

<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?

As recommended already: register a common event handler for the mouse click event.

MVVM is not concerned with code-behind. 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 is also not concerned with commands (or data binding or any framework concept in general). Commanding is part of the framework's infrastructure and MVVM does not care about frameworks - no design pattern does.
MVVM does not mean to use commands. 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. The code-behind file of a control is a partial class. It's part of the control and therefore part of the View.

Implement the user input event handler in the hosting control's code-behind. Here you must implement the Canvas related logic (UI logic).
If you want to encapsulate the logic, you can move it along with the Canvas to a new custom Control (or UserControl ).

MainWindow.xaml

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

MainWindow.xaml.cs

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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