全选的事件:WPF Datagrid

我正在使用WPF数据网格。 在数据网格中,用户具有列标题和行标题。

当列标题和行标题都可见时,在左上角我们有一个小的方形部分可用。 (列和行标题相交的左上角的横截面。)当我们点击它时,它会选择数据网格中的所有单元格。 那有什么事吗? 如果不是如何陷阱那个事件。 请指导我。

如果您需要有关此问题的任何其他信息,请与我们联系。

此致,Priyank

datagrid处理路由命令ApplicationCommand.SelectAll,因此如果网格具有焦点并按Ctrl-A,或者单击角按钮,则会选择所有单元格。 您可以通过在xaml中添加CommandBinding来自己处理此命令:

    

或者您可以在代码中添加命令绑定:

 public MyControl(){ InitializeComponent(); ... dataGrid.CommandBindings.Add(new CommandBinding(ApplicationCommands.SelectAll, SelectAll_Executed)); } 

但是,路由命令只能有一个处理程序,因此默认情况下添加此处理程序会阻止select all在数据网格中工作。 因此,在您的处理程序中,您需要调用SelectAll。

 private void SelectAll_Executed(object sender, ExecutedRoutedEventArgs e) { Debug.WriteLine("Executed"); dataGrid.SelectAll(); } 

这不是一个很好的解决方案,但你可以处理像“SelectionChanged”这样的事件,并检查所选项目的数量是否等于数据源中的项目数量

我宁愿避免在视图中使用代码,所以我这样做了: 在此处输入图像描述

在此处输入图像描述

左上角的CheckBox选择/取消全选。

该解决方案由两部分构成:附加属性和特殊的XAML结构:

1)。 附属物:

 public class DataGridSelectAllBehavior { public static bool GetValue(DependencyObject obj) { return (bool)obj.GetValue(ValueProperty); } public static void SetValue(DependencyObject obj, bool value) { obj.SetValue(ValueProperty, value); } public static readonly DependencyProperty ValueProperty = DependencyProperty.RegisterAttached("Value", typeof(bool), typeof(DataGridSelectAllBehavior), new PropertyMetadata(false, (o, e) => { var dg = DataGridSelectAllBehavior.GetDataGrid(o); CheckBox checkBox = o as CheckBox; if (checkBox.IsChecked == true) { dg.SelectAll(); } else { dg.UnselectAll(); } })); public static DataGrid GetDataGrid(DependencyObject obj) { return (DataGrid)obj.GetValue(DataGridProperty); } public static void SetDataGrid(DependencyObject obj, DataGrid value) { obj.SetValue(DataGridProperty, value); } public static readonly DependencyProperty DataGridProperty = DependencyProperty.RegisterAttached("DataGrid", typeof(DataGrid), typeof(DataGridSelectAllBehavior), new PropertyMetadata(null)); } 

2)XAML: