【问题标题】:WPF DataGrid - How detect if full row is selected?WPF DataGrid - 如何检测是否选择了整行?
【发布时间】:2017-12-07 20:08:32
【问题描述】:

我的 WPF 应用程序中有 DataGrid,我想在 SelectedCellsChanged 事件中运行一个函数,但前提是该行未完全选中,如果用户单击该行的标题会发生这种情况。

我的表格只有一列。

我试过下面的代码,rowContainer.IsSelected 的值总是假的。

我该怎么做?

Private Sub DataGridEx_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) Handles Me.SelectionChanged

    If SelectedCells.Count <> 1 Then
        Exit Sub
    End If

    If Not SelectedCells.First.Item.ToString.Contains("NewItemPlaceholder") Then

            Me.TheDispatcher.BeginInvoke(
                Sub()
                    Dim cell = SelectedCells.First
                    Dim index = Items.IndexOf(cell.Item) + 1
                    Dim rowContainer As DataGridRow = ItemContainerGenerator.ContainerFromIndex(index)

                    If rowContainer IsNot Nothing Then
                        If Not rowContainer.IsSelected Then
                            ' run a function here
                        End If
                    End If
                End Sub,
                DispatcherPriority.Input)

     End If

End Sub

【问题讨论】:

    标签: .net wpf vb.net


    【解决方案1】:

    获取选择单元格的行容器并检查其IsSelected 属性:

    private void DataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
    {
        DataGrid dg = sender as DataGrid;
        if (dg.SelectedCells != null && dg.SelectedCells.Count > 0)
        {
            var cell = dg.SelectedCells[0];
            var row = dg.ItemContainerGenerator.ContainerFromItem(cell.Item) as DataGridRow;
            if (row != null && row.IsSelected)
            {
                MessageBox.Show("row is selected...");
            }
        }
    }
    

    如果您使用的是 SelectionUnit 或 CellOrRowHeader,这应该可以工作。

    【讨论】:

      【解决方案2】:

      您可以做的一件事是将您的数据网格作为 FullRow、Cell 或 CellOrRowHeader 强制到 SelectionUnit

      dim dg = new DataGrid();
      dg.SelectionUnit == System.Windows.Controls.DataGridSelectionUnit.FullRow;
      dg.SelectionUnit == System.Windows.Controls.DataGridSelectionUnit.CellOrRowHeader;
      dg.SelectionUnit == System.Windows.Controls.DataGridSelectionUnit.Cell;
      

      在 XAML 中,您只需应用属性设置

      <DataGrid SelectionUnit="FullRow" ... >
      

      那么您应该能够简单地挂接到 SelectedCellsChanged 或 SelectionChanged 方法以对其进行操作...

      那么您不必担心仅选择一两个单元格的部分行,也不会触发您期望处理的整行。通过强制一整行,它将在其集合中每行一个条目。否则,如果您按单元格拥有它并且有 5 列宽,并且人在两行上选择了 3 个单元格,那么它将有 6 个单元格代表覆盖行的每个单独单元格的同一行..

      HTH

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-08-23
        • 2022-01-16
        • 2013-08-31
        • 1970-01-01
        • 1970-01-01
        • 2011-02-21
        • 1970-01-01
        相关资源
        最近更新 更多