在DataGridCell的CellEditingTemplate中查找TextBox

我在WPF中遇到问题,在选择单元格并处于编辑模式时,以编程方式访问DataGridTemplateColumn.CellEditingTemplate中的文本框。

这是我的DataGrid的XAML:

                

如何在选择单元格时访问该TextBox? 这是一个显示DataGrid可视树的图像,如果它可以帮助您:

DataGrid Visual Tree

我在DataGridCell GotFocus事件中尝试了以下操作,但没有运气。 它只是返回NULL,因为找不到它。

 private void DataGridCellGotFocus(object sender, RoutedEventArgs e) { var cell = sender as DataGridCell; var textBox = FindChild(cell, null); } 

FindChild方法的位置如下:

 ///  /// Finds a Child of a given item in the visual tree. ///  /// A direct parent of the queried item. /// The type of the queried item. /// x:Name or Name of child.  /// The first parent item that matches the submitted type parameter. /// If not matching item can be found, /// a null parent is being returned. public static T FindChild(DependencyObject parent, string childName) where T : DependencyObject { // Confirm parent and childName are valid. if (parent == null) return null; T foundChild = null; int childrenCount = VisualTreeHelper.GetChildrenCount(parent); for (int i = 0; i < childrenCount; i++) { var child = VisualTreeHelper.GetChild(parent, i); // If the child is not of the request child type child T childType = child as T; if (childType == null) { // recursively drill down the tree foundChild = FindChild(child, childName); // If the child is found, break so we do not overwrite the found child. if (foundChild != null) break; } else if (!string.IsNullOrEmpty(childName)) { var frameworkElement = child as FrameworkElement; // If the child's name is set for search if (frameworkElement != null && frameworkElement.Name == childName) { // if the child's name is of the request name foundChild = (T)child; break; } } else { // child element found. foundChild = (T)child; break; } } return foundChild; } 

我怀疑它与DataTemplate有关但我需要一些关于如何选择TextBox子元素的建议?

我认为你应该尽可能避免使用VisualTreeHelper 。 如果我理解,您可以在CellEditingCommand封装您的登录信息

            

您也可以使用“ 行为”

UPD

          

并触发动作

 public class TakeFocusAction : TriggerAction { protected override void Invoke(object parameter) { AssociatedObject.Focus(); } } 
 ContentPresenter presenter = e.Column.GetCellContent(e.Row); TextBox textBox = presenter.ContentTemplate.FindName("nameOfYourTextBox", presenter) as TextBox; 

我认为你应该处理PreparingCellForEdit :Sth

 void MainDataGrid_PreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e) { TextBox tb = e.Column.GetCellContent(e.Row) as TextBox; } 

请参阅: 用户编辑WPF DataGrid Cell时如何知道?