I wanted to solve this without needing to handle the listBoxItem double click event in the code-behind, and I didn't want to have to override the listBoxItem style (or define the style to override in the first place). I wanted to just fire a command when the listBox was doubleclicked.
I created an attached property like so (the code is very specific, but you can generalise it as required):
public class ControlItemDoubleClick : DependencyObject {
public ControlItemDoubleClick()
{
}
public static readonly DependencyProperty ItemsDoubleClickProperty =
DependencyProperty.RegisterAttached("ItemsDoubleClick",
typeof(bool), typeof(Binding));
public static void SetItemsDoubleClick(ItemsControl element, bool value)
{
element.SetValue(ItemsDoubleClickProperty, value);
if (value)
{
element.PreviewMouseDoubleClick += new MouseButtonEventHandler(element_PreviewMouseDoubleClick);
}
}
static void element_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
ItemsControl control = sender as ItemsControl;
foreach (InputBinding b in control.InputBindings)
{
if (!(b is MouseBinding))
{
continue;
}
if (b.Gesture != null
&& b.Gesture is MouseGesture
&& ((MouseGesture)b.Gesture).MouseAction == MouseAction.LeftDoubleClick
&& b.Command.CanExecute(null))
{
b.Command.Execute(null);
e.Handled = true;
}
}
}
public static bool GetItemsDoubleClick(ItemsControl element)
{
return (bool)element.GetValue(ItemsDoubleClickProperty);
}
}
I then declare my ListBox with the attached property and my target command:
<ListBox ItemsSource="{Binding SomeItems}"
myStuff:ControlItemDoubleClick.ItemsDoubleClick="true">
<ListBox.InputBindings>
<MouseBinding MouseAction="LeftDoubleClick" Command="MyCommand"/>
</ListBox.InputBindings>
</ListBox>
Hope this helps.