WELCOME

This blog is where I post about my consulting work with Microsoft Technologies, and other random tidbits that don't fit in my Photo Blog or my Iraq Blog.

Tuesday, March 31, 2009

Double-clicking on a ListBox in MVVM

Here is a quick code snippet that demonstrates doubleclicking on a WPF ListBox in MVVV. Note: This is using AttachedCommandBehavior V2.


<
ListBox Name="MyListBox">

<ListBox.Resources>

<Style
TargetType
="{x:Type ListBoxItem}">

<Setter
Property
="IsSelected"
Value
="{Binding
Path
=IsSelected, Mode=TwoWay}"/>

<Setter
Property
="acb:CommandBehavior.Event"
Value
="MouseDoubleClick" />

<Setter
Property
="acb:CommandBehavior.Command"

Value="{Binding ElementName=Window1,
Path
=DataContext.MyDoubleClickCommand}" />

<Setter
Property
="acb:CommandBehavior.CommandParameter"
Value
="{Binding}"
/>

</Style>

   


</
ListBox.Resources>

</ListBox>

Key points to note:
  • Setting the CommandParameter to "{Binding}" passes the item that is bound to this ListBoxItem as a parameter to the command we are calling (answering the question: "What item was double clicked?".
  • Using a Style is a quick way to insert the stuff we want into each ListBoxItem.
  • This example is also binding IsSelected so that we can determine the SelectedItem(s) from within the view model (this isn't required to make double click work... I just thought it was interesting to leave it in the code snippet since it took me a while to figure it out...)