Search code examples
c#wpfxamlmvvm

How to bind a list view to a double click event that triggers an Icommand?


In WPF, my ListView has ListView.InputBindings where I want to add a MouseBinding for a left double click that triggers an ICommand.

Right now my code looks like this:

<ListView Name="ListViewName" 
          Grid.Row="1" 
          Grid.Column="0"
          ItemsSource="{Binding DefinedItems}"
          ScrollViewer.HorizontalScrollBarVisibility="Auto" 
          ScrollViewer.VerticalScrollBarVisibility="Auto">
  <ListView.InputBindings>
    <KeyBinding Key="Delete" 
                Command="{Binding DeleteSelectedItems}" 
                CommandParameter="{Binding SelectedItems, ElementName=ItemsListView}">
    </KeyBinding>
    <KeyBinding Key="Space" 
                Command="{Binding SwitchItemState}" 
                CommandParameter="{Binding SelectedItems, ElementName=ItemsListView}">
    </KeyBinding>
    <MouseBinding Gesture="LeftDoubleClick" 
                  Command="{Binding GoToItem}" 
                  CommandParameter="{Binding SelectedItems, ElementName=ItemsListView}">
    </MouseBinding>
  </ListView.InputBindings>

I have the command set up on the viewModel but Im confused as to where the mouse event c# code goes or if I even need it. thanks in advance!


Solution

  • There are various third party packages to introduce event behaviors which allow events to be bound to commands, but it's basically using a impact driver to hang a small picture. In the end, make your life easier and just use an event handler than then executes the ICommand in code behind.

    <ListView Name="ListViewName" 
              Grid.Row="1" 
              Grid.Column="0"
              ItemsSource="{Binding DefinedItems}"
              ScrollViewer.HorizontalScrollBarVisibility="Auto" 
              ScrollViewer.VerticalScrollBarVisibility="Auto"
              MouseDoubleClick="ListViewName_MouseDoubleClick"/>
    
    private void ListViewName_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        var viewModel = (MyViewModel)DataContext;
        if (viewModel.GoToItem.CanExecute(ListViewName.SelectedItem))
            viewModel.GoToItem.Execute(ListViewName.SelectedItem);
    }
    

    Remember, MVVM doesn't mean "no code behind" as is often suggested, it just means the code behind should be visual logic that adheres to the one way relationship, which this solution does.