【问题标题】:WPF Datagrid "Select All" button - "Unselect All" too?WPF Datagrid“全选”按钮 - “取消全选”?
【发布时间】:2010-12-02 09:13:32
【问题描述】:

我想知道是否可以向数据网格左上角的“全选”按钮添加功能,以便取消选择所有行?我有一个附加到执行此操作的按钮的方法,但是如果我可以从“全选”按钮触发此方法以将功能保持在视图的同一部分,那就太好了。这个“全选”按钮是否可以添加代码,如果可以,如何到达该按钮?我找不到任何示例或建议。

【问题讨论】:

    标签: c# .net wpf datagrid wpfdatagrid


    【解决方案1】:

    好的,经过大量搜索后,我发现如何从 Colin Eberhardt 那里获得按钮:

    Styling hard-to-reach elements in control templates with attached behaviours

    然后我在他的类中扩展了“Grid_Loaded”方法,为按钮添加了一个事件处理程序,但记得先删除默认的“全选”命令(否则,在运行我们添加的事件处理程序后,该命令会得到跑步)。

    /// <summary>
    /// Handles the DataGrid's Loaded event.
    /// </summary>
    /// <param name="sender">Sender object.</param>
    /// <param name="e">Event args.</param>
    private static void Grid_Loaded(object sender, RoutedEventArgs e)
    {
        DataGrid grid = sender as DataGrid;
        DependencyObject dep = grid;
    
        // Navigate down the visual tree to the button
        while (!(dep is Button))
        {
            dep = VisualTreeHelper.GetChild(dep, 0);
        }
    
        Button button = dep as Button;
    
        // apply our new template
        ControlTemplate template = GetSelectAllButtonTemplate(grid);
        button.Template = template;
        button.Command = null;
        button.Click += new RoutedEventHandler(SelectAllClicked);
    }
    
    /// <summary>
    /// Handles the DataGrid's select all button's click event.
    /// </summary>
    /// <param name="sender">Sender object.</param>
    /// <param name="e">Event args.</param>
    private static void SelectAllClicked(object sender, RoutedEventArgs e)
    {
        Button button = sender as Button;
        DependencyObject dep = button;
    
        // Navigate up the visual tree to the grid
        while (!(dep is DataGrid))
        {
            dep = VisualTreeHelper.GetParent(dep);
        }
    
        DataGrid grid = dep as DataGrid;
    
        if (grid.SelectedItems.Count < grid.Items.Count)
        {
            grid.SelectAll();
        }
        else
        {
            grid.UnselectAll();
        }
    
        e.Handled = true;
    }
    

    基本上,如果没有选择任何行,则“全选”,否则“取消全选”。它的工作原理与您期望全选/取消全选工作非常相似,老实说,我不敢相信他们没有让命令默认执行此操作,也许在下一个版本中。

    希望这对某人有所帮助, 干杯, 会

    【讨论】:

    • 谢谢 - 如果包含 'GetSelectAllButtonTemplate()' 的定义,代码示例将是完整的。
    【解决方案2】:

    我们可以添加一个命令绑定来处理 selectall 事件。

    见:Event for Select All: WPF Datagrid

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-13
      • 1970-01-01
      • 1970-01-01
      • 2015-06-12
      • 1970-01-01
      • 2022-11-18
      相关资源
      最近更新 更多