如何从WPF中的DataGridCell找到其所有者DataGrid和DataGridRow? [英] How to find its owner DataGrid and DataGridRow from DataGridCell in WPF?

查看:835
本文介绍了如何从WPF中的DataGridCell找到其所有者DataGrid和DataGridRow?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个用于DataGrid的Command的事件处理程序中,我在ExecutedRoutedEventArgs中获取DataGridCell。但是,我无法弄清楚如何获取相关的DataGrid和DataGridRow。您的帮助非常感激。

解决方案

您可能希望设置某种 RelativeSource 绑定可以通过 {RelativeSource FindAncestor,AncestorType = {x:Type DataGrid}}获得父网格/行但是你的问题让我想起来...



你可以:



使用反射:

  var gridCell = ....; 
var parentRow = gridCell
.GetType()
.GetProperty(RowOwner,
BindingFlags.NonPublic | BindingFlags.Instance)
.GetValue(null)as DataGridRow ;

使用 VisualTreeHelper

  var gridCell = ...; 
var parent = VisualTreeHelper.GetParent(gridCell);
while(parent!= null&& parent.GetType()!= typeof(DataGridRow))
{
parent = VisualTreeHelper.GetParent(parent);
}


In an event handler for a Command for a DataGrid, I get DataGridCell in ExecutedRoutedEventArgs. However, I couldn't figure out how to get its associated DataGrid and DataGridRow. Your help is much appreciated.

解决方案

You probably want to set some sort of RelativeSource binding that can get you the "parent grid/row" via a {RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, but your question got me thinking...

You could:

Use Reflection:

var gridCell = ....;
var parentRow = gridCell
         .GetType()
         .GetProperty("RowOwner", 
               BindingFlags.NonPublic | BindingFlags.Instance)
         .GetValue(null) as DataGridRow;

Use the VisualTreeHelper:

var gridCell = ...;
var parent = VisualTreeHelper.GetParent(gridCell);
while(parent != null && parent.GetType() != typeof(DataGridRow))
{
    parent = VisualTreeHelper.GetParent(parent);
}

这篇关于如何从WPF中的DataGridCell找到其所有者DataGrid和DataGridRow?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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