Silverlight Commands – Data grid row selected

following on from http://thoughtjelly.blogspot.com/2009/09/silverlight-prism-commands-textchanged.html and in response to John Papa’s PDC talk http://johnpapa.net/silverlight/mvvm-and-prism-demo-for-pdc09-silverlight-session. 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;
ExecuteCommand();
}
}

And

public static class DataGridRowSelected
{
private static readonly DependencyProperty DataGridRowSelectedCommandBehaviorProperty = DependencyProperty.RegisterAttached(
"SelectedCommandBehavior",
typeof(DataGridRowSelectedCommandBehavior),
typeof(DataGridRowSelected),
null);

public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached(
"Command",
typeof(ICommand),
typeof(DataGridRowSelected),
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:

WordPress.com Logo

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

Google photo

You are commenting using your Google 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 WordPress.com Website.

Up ↑

%d bloggers like this: