Silverlight Commands – Data grid row selected

following on from and in response to John Papa’s PDC talk Another highly useful command behaviour is for DataGridRowSelected.
This also gets over the issues described here and here. The code (as written by John Papa) is:

public class DataGridRowSelectedCommandBehavior : CommandBehaviorBase
public DataGridRowSelectedCommandBehavior(DataGrid selectableObject)
: base(selectableObject)
selectableObject.SelectionChanged += OnSelectionChanged;

private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
this.CommandParameter = this.TargetObject.SelectedItem;


public static class DataGridRowSelected
private static readonly DependencyProperty DataGridRowSelectedCommandBehaviorProperty = DependencyProperty.RegisterAttached(

public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached(
new PropertyMetadata(OnSetCommandCallback));

public static void SetCommand(DataGrid dataGrid, ICommand command)
dataGrid.SetValue(CommandProperty, command);

public static ICommand GetCommand(DataGrid dataGrid)
return dataGrid.GetValue(CommandProperty) as ICommand;

private static void OnSetCommandCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
var dataGrid = dependencyObject as DataGrid;
if (dataGrid != null)
GetOrCreateBehavior(dataGrid).Command = e.NewValue as ICommand;

private static DataGridRowSelectedCommandBehavior GetOrCreateBehavior(DataGrid dataGrid)
var behavior = dataGrid.GetValue(DataGridRowSelectedCommandBehaviorProperty) as DataGridRowSelectedCommandBehavior;
if (behavior == null)
behavior = new DataGridRowSelectedCommandBehavior(dataGrid);
dataGrid.SetValue(DataGridRowSelectedCommandBehaviorProperty, behavior);

return behavior;

2 thoughts on “Silverlight Commands – Data grid row selected

Add yours

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

A Website.

Up ↑

%d bloggers like this: