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.