Adding MouseBindings to Items in a databound WPF ListView

大城市里の小女人 提交于 2019-12-05 20:48:47

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.

Stonetip

I was able to work around this by doing the following:

1) I added a reference to the System.Windows.Interactivity DLL (found it in C:\Program Files (x86)\Microsoft SDKs\Expression\Blend\.NETFramework\v4.0\Libraries)

2) Added this to my XAML file:

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

3) Added this inside my ListView:

<ListView ...>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseDoubleClick">
            <i:InvokeCommandAction Command="{x:Static local:MainWindow.RoutedCommandEditSelectedRecordWindow}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
    ...

</ListView>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!