Silverlight InvokeCommandAction Bind Button DataContext To UserControl DataContext

By Robbe Morris

In Silverlight 4.0, you often times you need to bind to an ObservableCollection<T> in your ListBox, DataGrid, etc. but also bind to events/commands using InvokeCommandAction that exist in your ViewModel. It gives you a way to send the current record in the list as a parameter to method fired from your Button/Hyperlinkbutton click event. The following example shows how.

Here's a standard ListBox control.  The .DataContext of our main user control is bound to an instance
of our ViewModel class.  The ViewModel exposes a public command MoveCustomerCommand(Customer record).
The MoveCustomerCommand would be configured to use a DelegateCommand not shown here.
The ViewModel also exposes an ObservableCollection<Customer> called Customers that is used
as the ListBox.ItemSource value.

In the InvokeCommandAction tag, we set the path to use the DataContext of our ListBox control
named "CustomerListControl".  The CommandParameter="{Binding}" sets the value to the current
record in the collection/DataTemplate.

<ListBox Name="CustomerListControl" ItemsSource="{Binding Path=Customers,Mode=TwoWay}" >
        <i:EventTrigger EventName="Click">
          <i:InvokeCommandAction Command="{Binding Path=DataContext.MoveCustomerCommand,
        <StackPanel Orientation="Horizontal">
           <TextBlock Text="{Binding Path=FirstName}"  />
           <TextBlock Text="{Binding Path=LastName}"  />

For more information on the DelegateCommand, here is a good example:

Silverlight InvokeCommandAction Bind Button DataContext To UserControl DataContext  (4196 Views)