如何确定 WPF DataGrid 是不是处于编辑模式? [复制]

Posted

技术标签:

【中文标题】如何确定 WPF DataGrid 是不是处于编辑模式? [复制]【英文标题】:How to determine whether a WPF DataGrid is in edit mode? [duplicate]如何确定 WPF DataGrid 是否处于编辑模式? [复制] 【发布时间】:2011-03-17 19:24:28 【问题描述】:

可能重复:Code to check if a cell of a DataGrid is currently edited

有没有办法确定 WPF DataGrid 是否处于编辑模式/当前正在编辑哪一行?

【问题讨论】:

【参考方案1】:

VB.NET

<Extension>
Public Function GetContainerFromIndex(Of TContainer As DependencyObject) _
    (ByVal itemsControl As ItemsControl, ByVal index As Integer) As TContainer
  Return DirectCast(
    itemsControl.ItemContainerGenerator.ContainerFromIndex(index), TContainer)
End Function

<Extension>
Public Function IsEditing(ByVal dataGrid As DataGrid) As Boolean
  Return dataGrid.GetEditingRow IsNot Nothing
End Function

<Extension>
Public Function GetEditingRow(ByVal dataGrid As DataGrid) As DataGridRow
  Dim sIndex = dataGrid.SelectedIndex
  If sIndex >= 0 Then
    Dim selected = dataGrid.GetContainerFromIndex(Of DataGridRow)(sIndex)
    If selected.IsEditing Then Return selected
  End If

  For i = 0 To dataGrid.Items.Count - 1
    If i = sIndex Then Continue For
    Dim item = dataGrid.GetContainerFromIndex(Of DataGridRow)(i)
    If item.IsEditing Then Return item
  Next

  Return Nothing
End Function

C#:

public static TContainer GetContainerFromIndex<TContainer>
  (this ItemsControl itemsControl, int index)
    where TContainer : DependencyObject

  return (TContainer)
    itemsControl.ItemContainerGenerator.ContainerFromIndex(index);


public static bool IsEditing(this DataGrid dataGrid)

  return dataGrid.GetEditingRow() != null;


public static DataGridRow GetEditingRow(this DataGrid dataGrid)

  var sIndex = dataGrid.SelectedIndex;
  if (sIndex >= 0)
  
    var selected = dataGrid.GetContainerFromIndex<DataGridRow>(sIndex);
    if (selected.IsEditing) return selected;
  

  for (int i = 0; i < dataGrid.Items.Count; i++)
  
    if (i == sIndex) continue;
    var item = dataGrid.GetContainerFromIndex<DataGridRow>(i);
    if (item.IsEditing) return item;
  

  return null;

【讨论】:

以上是关于如何确定 WPF DataGrid 是不是处于编辑模式? [复制]的主要内容,如果未能解决你的问题,请参考以下文章

WPF DataGrid - 如何自动退出编辑模式?

(WPF Datagrid)如何确定项目的列索引

在WPF DataGrid中按Enter键时将焦点移动到下一个单元格?

无法编辑我的 DataGrid WPF Framework 4.5 的单元格

如何在wpf中创建DataGrid ReadOnly的第一行

wpf datagrid 滚动条如何设置宽度和颜色