WPF数据网格中的“全选”按钮 - 是否也有“取消全选”?

12

我想知道是否可以在数据表格左上角的“全选”按钮中添加功能,使它也能取消选择所有行?我已经将一个方法附加到一个按钮上来实现这个功能,但是如果我可以从“全选”按钮中触发这个方法的话,那就太好了,因为这样可以在视图的同一部分保持功能性。这个“全选”按钮可以添加代码吗?如果可以,如何访问该按钮?我没有找到任何示例或建议。

2个回答

13

经过大量搜索,我发现了如何从Colin Eberhardt的这里获取到按钮,链接如下:

使用关联行为在控件模板中对难以获取的元素进行样式设置

然后我扩展了他的类中的“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;
}

基本上,如果没有选择任何行,则“选择全部”,否则“取消选择全部”。它的工作方式与您期望的选择/取消选择全部功能几乎相同。老实说,我无法相信他们没有默认使命令执行此操作,也许在下一个版本中会有吧。

希望这能帮助某些人, 谢谢, 威尔


2
谢谢 - 如果包括 'GetSelectAllButtonTemplate()' 的定义,代码示例将会完整。 - PandaWood

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接