Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Linq;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Input;
- namespace Client.Extensions
- {
- /// <summary>
- /// Extension to handle a DataGrid's SelectionChanged event to call a command
- /// <remarks>
- /// ext:DataGridSelectedRows.Command="{Binding YourCommand}"
- /// </remarks>
- /// </summary>
- public static class DataGridSelectedRows
- {
- public static readonly DependencyProperty CommandProperty =
- DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(DataGridSelectedRows), new UIPropertyMetadata(null, OnCommandChanged));
- public static ICommand GetCommand(DependencyObject obj)
- {
- return (ICommand)obj.GetValue(CommandProperty);
- }
- public static void SetCommand(DependencyObject obj, ICommand value)
- {
- obj.SetValue(CommandProperty, value);
- }
- static void OnCommandChanged(DependencyObject target, DependencyPropertyChangedEventArgs args)
- {
- if (args.NewValue == null)
- return;
- var dataGrid = target as DataGrid;
- if (dataGrid == null)
- return;
- if (args.OldValue != null)
- dataGrid.SelectionChanged -= dataGrid_SelectionChanged;
- if(args.NewValue != null)
- dataGrid.SelectionChanged += dataGrid_SelectionChanged;
- }
- static void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- var dataGrid = sender as DataGrid;
- if (dataGrid == null)
- return;
- var command = GetCommand(dataGrid);
- if (command != null)
- {
- var cmdParam = dataGrid.SelectedItems.Cast<object>();
- if (command.CanExecute(cmdParam))
- command.Execute(cmdParam);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment