代码之家  ›  专栏  ›  技术社区  ›  google dev

WPF DataGrid-如何检测是否选择了整行?

  •  0
  • google dev  · 技术社区  · 8 年前

    我的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
    
    2 回复  |  直到 8 年前
        1
  •  1
  •   mm8    8 年前

    获取select单元格的行容器并检查其 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
  •  0
  •   DRapp    8 年前

    您可以做的一件事是强制将数据网格作为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列宽,并且person在两行上选择了3个单元格,则对于覆盖行的每个单独单元格,它将有6个表示同一行的单元格。。

    HTH公司

    推荐文章