当SelectionMode =“扩展"时,如何让DataGrid在单击时取消选择? [英] How can I get a DataGrid to unselect on click when SelectionMode="Extended"?

查看:21
本文介绍了当SelectionMode =“扩展"时,如何让DataGrid在单击时取消选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

WPF DataGrid 的默认行为是选择何时单击一行,如果 SelectionMode="Extended" 这是我想要的,但是我也希望行取消选择,如果它之前已经被点击.

The default behaviour of a WPF DataGrid is to select when a row is clicked if SelectionMode="Extended" which is what I want, however I also wish for the row to un-select if it was previously already selected when clicked.

我尝试了以下方法,一旦选中该行就会取消选择该行,看来行选择发生在鼠标单击事件之前.

I have tried the following which will unselect the row as soon as it's selected, it seems the row selection occurs before the mouse click event.

private void DoGridMouseLeftButtonUp(object sender, MouseButtonEventArgs args) {
    // Get source row.
    DependencyObject source = (DependencyObject)args.OriginalSource;
    var row = source.FindParent<DataGridRow>();
    if (row == null)
        return;
    // If selected, unselect.
    if (row.IsSelected) {
        row.IsSelected = false;
        args.Handled = true;
    }
}

我使用以下网格绑定到此事件的位置.

Where I am binding to this event with the following grid.

<DataGrid SelectionMode="Extended"
          SelectionUnit="FullRow"
          MouseLeftButtonUp="DoGridMouseLeftButtonUp">

推荐答案

我设法解决了这个问题,而不是在网格本身上处理事件,而是在单元格上处理它们,这涉及到 DataGridCell 的事件设置器如下:

I have managed to solve this by instead of handling events on the grid itself to handle them on the cell instead, this involves an event setter for DataGridCell as follows:

<DataGrid SelectionMode="Extended"
          SelectionUnit="FullRow">
    <DataGrid.Resources>
        <Style TargetType="{x:Type DataGridCell}">
            <EventSetter Event="PreviewMouseLeftButtonDown"
                         Handler="DoCheckRow"/>
        </Style>
    </DataGrid.Resources>
    <!-- Column mapping omitted. -->
</DataGrid>

事件处理程序代码.

public void DoCheckRow(object sender, MouseButtonEventArgs e) {
    DataGridCell cell = sender as DataGridCell;
    if (cell != null && !cell.IsEditing) {
        DataGridRow row = FindVisualParent<DataGridRow>(cell);
        if (row != null) {
            row.IsSelected = !row.IsSelected;
            e.Handled = true;
        }
    }
}

我的网格是只读的,所以这里忽略任何编辑行为.

My grid is read only so any edit behavior is ignored here.

这篇关于当SelectionMode =“扩展"时,如何让DataGrid在单击时取消选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆