WPF ListBoxItem double-click?
You could always override the ListItem Control Template and handle the double click event inside the template, for example in an invisible border that contains the normal contents of the ListBox.
This article shows you how to use a ControlTemplate with a ListBoxItem. Beyond that, simply add the handler to the outermost element of your control template.
If you have Expression Blend, you can use it to extract the existing control template for you to modify so that you do not have to do as much work to ensure that the new list box behaves the same as the old.
It turns out there is a MouseDoubleClick event for the ListBox. I added this event to my ListBox and had the event handler process my task, copying the selected item to another ListBox. So, now whenever I double-click on an item, it gets copied.
It is possible to bind commands with parameters to ListBoxItem
s without using code-behind or attached behaviors, simply by using InputBindings
with a MouseBinding
, as shown before in this answer.
Example ListBox
with MouseBinding
for LeftDoubleClick
:
<ListBox ItemsSource="{Binding MyDataSource}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding MySourceItemName}">
<TextBlock.InputBindings>
<MouseBinding MouseAction="LeftDoubleClick"
Command="{Binding DataContext.MyCommand, RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}"
CommandParameter="{Binding MySourceItemId}" />
</TextBlock.InputBindings>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
If the command is defined in the same DataContext as the ItemsSource
of the ListBox
, it can be bound by using the RelativeSource
binding as included in the example.
If you are using databinding, then this problem is very easy to solve
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ObjectName}"
MouseDown="TextBlock_MouseDown"/>
</DataTemplate>
</ListBox.ItemTemplate>
Then in your code behind, check for a double click as follows
private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ClickCount>=2)
{
....
}
}
If your double clicked item was not selected before the double click, then it wont appear selected in the event handler. Your logic within that handler needs to bear this in mind