c# - WPF Datagrid "Select All"按钮 - "Unselect All"也是?

标签 c# .net wpf datagrid wpfdatagrid

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

最佳答案

好的,经过大量搜索后,我发现了如何从 Colin Eberhardt 那里找到按钮,在这里:

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

然后我在他的类中扩展了“Grid_Loaded”方法来为按钮添加一个事件处理程序,但记得先删除默认的'Select All'命令(否则,在运行我们添加的事件处理程序后,命令获取运行)。

/// <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;
}

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

无论如何,希望这对某人有所帮助, 干杯, 将

关于c# - WPF Datagrid "Select All"按钮 - "Unselect All"也是?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1493491/

相关文章:

c# - 将焦点设置在屏幕顶部 jquery

.net - LINQ 查询的索引

WPF - 使用 JpegBitmapDecoder 将文件转换为 Byte[] 到 BitmapSource

wpf - 在容器 View 模型中嵌套 View 模型是否违反 MVVM?

c# - 面向 C/C++ 用户的 C# 简介

c# - Silverlight/.net 的条码阅读器组件、资源、推荐、动物之森?天啊

c# - 这个开关/模式匹配的想法有什么好处吗?

.net - Visual Studio 设计器表单中 ToolStrip 的自定义 ToolStripButton

c# - 有谁知道一个好的 Subversion C# API?

c# - Datagrid 组合框使 relativsource 工作