Adding MouseBindings to Items in a databound WPF ListView

Michael Menne picture Michael Menne · Jan 25, 2010 · Viewed 7.8k times · Source

I'm trying to get a command in my ViewModel executed when the user clicks on a item in a ListView. When I add a ListViewItem in XAML I can just add a MouseBinding to its InputBindings.

<ListView>
<ListView.View>
   <GridView>
      <GridViewColumn Header="Test" />
   </GridView>
   </ListView.View>
   <ListViewItem Content="Item 1" >
      <ListViewItem.InputBindings>
         <MouseBinding Gesture="LeftDoubleClick" Command="{Binding DoubleClickCommand}" />
      </ListViewItem.InputBindings>
 </ListViewItem>
 </ListView>

But how can this be achived in a databound ListView?

<ListView ItemsSource="{Binding Patients}">
<ListView.View>
    <GridView>
        <GridViewColumn Header="Test" />
    </GridView>
    <!-- How to set the MouseBinding for the generated ListViewItems?? -->
</ListView.View>

I already got a solution by defining ListViewItem style and replacing the ControlTempalte of the ListViewItem. Though, I hope there is an easier solution.

Sincerely, Michael

Answer

Ray Burns picture Ray Burns · Jan 26, 2010

Replacing the ControlTemplate on ListViewItem using a style is not a bad solution. In fact, it would probably be my first choice.

Another way of accomplishing the same kind is to use a custom attached property on your ListViewItem style:

<Style TargetType="ListViewItem">
  <Setter Property="local:AddToInputBinding.Binding">
    <Setter.Value>
      <MouseBinding Gesture="LeftDoubleClick" Command="{Binding DoubleClickCommand}" />    
    </Setter.Value>
  </Setter>
  ...

To do this you need to create the MyBindingHandler.AddBinding attached property:

public class AddToInputBinding
{
  public static InputBinding GetBinding(... // create using propa snippet
  public static void SetBinding(...
  public static readonly DependencyProperty BindingProperty = DependencyProperty.RegisterAttached(
    "Binding", typeof(InputBinding), typeof(AddToInputBinding), new PropertyMetadata
  {
    PropertyChangedCallback = (obj, e) =>
    {
      ((UIElement)obj).InputBindings.Add((InputBinding)e.NewValue);
    }
  }));
}

This could be expanded to handle multiple bindings, but you get the idea: This class allows you to add an InputBinding inside any style.

This solution may be preferable over what you're doing because the DoubleClick binding is defined directly on the ListBoxItem not on another control inside its template. But I think it mostly just comes down to personal preference.