Silverlight InvokeCommandAction Bind Button DataContext To UserControl DataContext

By Robbe Morris
Access over 40 UI widgets with everything from interactive menus to rich charts.

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}" >
<ListBox.ItemTemplate>
<DataTemplate>
    <HyperlinkButton>
      <i:Interaction.Triggers>
        <i:EventTrigger EventName="Click">
          <i:InvokeCommandAction Command="{Binding Path=DataContext.MoveCustomerCommand,
                                                                           ElementName=CustomerListControl}"
       
                                               CommandParameter="{Binding}"/>
        </i:EventTrigger>
      </i:Interaction.Triggers>
     <HyperlinkButton.Content>
        <StackPanel Orientation="Horizontal">
           <TextBlock Text="{Binding Path=FirstName}"  />
           <TextBlock Text="{Binding Path=LastName}"  />
        </StackPanel>
      </HyperlinkButton.Content>
    </HyperlinkButton>
  </DataTemplate>
</ListBox.ItemTemplate>
</ListBox>


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

http://msmvps.com/blogs/deborahk/archive/2011/02/12/silverlight-simple-mvvm-commanding.aspx

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