Handling PreviewMouseDown and PreviewMouseUp events in Prism

Viewed 117

I have a Prism application and I'm attempting to bind PreviewMouseDown and PreviewMouseUp button events in my view to commands in my view model. When I run the code I see the following exception:

enter image description here

As a workaround, I'm currently binding to methods in the view and use a reference to the data context of the view model to execute the command. This works but doesn't seem correct because the view now has knowledge of the view model.

What is the proper way to handle something like this?

1 Answers

You cannot bind events to commands like, for example, the Command property of a button.

Luckily, you don't need to, because you have the Command property. It even disables the button if the command returns false from CanExecute.

If you have something other than a button or something other than MouseDown, you can use InvokeCommandAction (from Prism or from Interactivity)...

xmlns:i="http://schemas.microsoft.com/xaml/behaviors"

<i:Interaction.Triggers>
    <i:EventTrigger EventName="MouseDown">
        <prism:InvokeCommandAction Command="{Binding MyCommand}"/>
        <!-- or -->
        <i:InvokeCommandAction Command="{Binding MyCommand}"/>
    </i:EventTrigger>
</i:Interaction.Triggers>  
Related