Jonas Verdickt
Jonas Verdickt

Reputation: 319

Executing a Command when a ListView is DoubleClicked. (WPF - MVVM)

I am having some difficulties binding a command (ICommand) to the MouseBinding of a ListView. I used this piece of XAML code to test the different mouse gestures:

<ListView.InputBindings>
    <MouseBinding Command="{Binding OpenSOACommand}" Gesture="LeftClick" />
    <MouseBinding Command="{Binding OpenSOACommand}" Gesture="MiddleClick" />
    <MouseBinding Command="{Binding OpenSOACommand}" Gesture="LeftDoubleClick" />
</ListView.InputBindings>

The LeftClick and LeftDoubleClick gestures aren't triggered, yet the MiddleClick mouse binding works perfect (I have tested the mouse bindings one at a time as well...).

Is there a difference in the way the LeftDoubleClick and MiddleClick Gesture is handled? And if there is, how can I bind my ICommand to the LeftDoubleClick gesture?

Thanks!

Upvotes: 2

Views: 6367

Answers (2)

Rachel
Rachel

Reputation: 132568

The default Click event for the ListView is marking the event as handled. Try using PreviewLeftClick and PreviewLeftDoubleClick instead

EDIT

Since MouseBindings does not contain a PreviewLeftClick or PreviewLeftDoubleClick, try using the AttachedCommandBehavior code found here which allows you to attach a Command to just about any Event

For example,

<ListView local:CommandBehavior.Event="PreviewMouseDown" 
          local:CommandBehavior.Command="{Binding OpenSOACommand}" />

Upvotes: 4

Arcturus
Arcturus

Reputation: 27055

This is because your ListViewItems of your ListView will swallow your LeftClick events and convert them into nice SelectionChanged events. Since the ListViewItems will not respond to MiddleClick, this will work as expected.

You might want to get 'in front' of this click by handling the matching Preview equivalent of the event.

<ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem">
        <EventSetter Event="MouseDoubleClick" Handler="OnItemDoubleClick"/>
    </Style>
</ListView.ItemContainerStyle>

And invoke the command in the handler:

private void OnItemDoubleClick(object sender, MouseButtonEventArgs e)
{
     OpenSOACommand.Execute(null, this);
}

Upvotes: 1

Related Questions