C# DataGridColumn标题中的组合框-如何区分列?

C# DataGridColumn标题中的组合框-如何区分列?,c#,wpf,wpfdatagrid,C#,Wpf,Wpfdatagrid,我在DataGrid列的标题中有一个组合框。我想处理组合框的SelectionChanged事件,但我需要知道哪个控件(在哪个列的标题中)生成了该事件。控件通过调用列构造函数中分配给HeaderTemplate的静态资源DataTemplate放入标题中 我想使用列数据上下文在组合框上设置一些标识数据,但我无法访问该上下文。我可以轻松访问DataGrid数据模型上下文,但所有组合框(列)的数据都是相同的 知道如何解析哪个列标题组合框生成了事件吗?“哪个列标题组合框生成了事件?” (ComboBo

我在
DataGrid
列的标题中有一个
组合框。我想处理组合框的
SelectionChanged
事件,但我需要知道哪个控件(在哪个列的标题中)生成了该事件。控件通过调用列构造函数中分配给
HeaderTemplate
的静态资源
DataTemplate
放入标题中

我想使用列数据上下文在
组合框上设置一些标识数据,但我无法访问该上下文。我可以轻松访问
DataGrid
数据模型上下文,但所有
组合框(列)的数据都是相同的

知道如何解析哪个列标题组合框生成了事件吗?

“哪个列标题组合框生成了事件?”
(ComboBox)sender
是生成事件的ComboBox的句柄

如果需要访问标题或包含该组合框的列,可以使用VisualTreeHelper,如下所述:

根据您问题中的信息,该线程中的此答案可能就是您正在寻找的(John Myczek)-sub out
Window
类型:

可以使用VisualTreeHelper查找控件。下面是一个方法 使用VisualTreeHelper查找指定 类型。您可以使用VisualTreeHelper以其他方式查找控件 还有

public static class UIHelper
{
   /// <summary>
   /// Finds a parent of a given item on the visual tree.
   /// </summary>
   /// <typeparam name="T">The type of the queried item.</typeparam>
   /// <param name="child">A direct or indirect child of the queried item.</param>
   /// <returns>The first parent item that matches the submitted type parameter. 
   /// If not matching item can be found, a null reference is being returned.</returns>
   public static T FindVisualParent<T>(DependencyObject child)
     where T : DependencyObject
   {
      // get parent item
      DependencyObject parentObject = VisualTreeHelper.GetParent(child);

      // we’ve reached the end of the tree
      if (parentObject == null) return null;

      // check if the parent matches the type we’re looking for
      T parent = parentObject as T;
      if (parent != null)
      {
         return parent;
      }
      else
      {
         // use recursion to proceed with next level
         return FindVisualParent<T>(parentObject);
      }
   }
}
公共静态类UIHelper
{
/// 
///在可视树上查找给定项的父项。
/// 
///查询项的类型。
///查询项的直接或间接子项。
///与提交的类型参数匹配的第一个父项。
///如果找不到匹配项,则返回空引用。
公共静态T FindVisualParent(DependencyObject子级)
其中T:DependencyObject
{
//获取父项
DependencyObject parentObject=VisualTreeHelper.GetParent(子级);
//我们已经到了树的尽头
if(parentObject==null)返回null;
//检查父项是否与我们要查找的类型匹配
T parent=parentObject作为T;
如果(父项!=null)
{
返回父母;
}
其他的
{
//使用递归继续下一个级别
返回FindVisualParent(父对象);
}
}
}
可以这样称呼:

Window owner = UIHelper.FindVisualParent<Window>(myControl);
windowowner=UIHelper.findvisualpart(myControl);

谢谢不知怎的,我没有想到要走上视觉树。。。我很想在事件处理程序中获取对列的引用,因此无法看到树的林。现在我可以找到标题(而不是列),并且可以使用标题的标记属性中的信息来处理事件。