如何从ItemTemplate类中获取TreeView?

时间:2015-07-15 17:31:38

标签: wpf treeview itemtemplate

我有一个像这样的TreeView类,它有我自己的类“EntryPanel”作为ItemTemplate:

<TreeView x:Class="PowerNote.MyEntriesView"             
         xmlns:local="clr-namespace:PowerNote"
         DataContext="{Binding RelativeSource={RelativeSource Self}}"
         ItemsSource = "{Binding viewStudents}">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Children}">
            <local:EntryPanel/>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

在我的EntryPanel.xaml.cs代码中,我想访问TreeView。我尝试过Parent和TemplateParent,但两者都不起作用。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

尝试以这种方式找到父母。

public static T TryFindParent<T>(this DependencyObject child)
where T : DependencyObject
{
   //get parent item
   DependencyObject parentObject = GetParentObject(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 TryFindParent<T>(parentObject);
   }
 }

这个会找到父对象。

 public static DependencyObject GetParentObject(this DependencyObject child)
 {
   if (child == null) return null;

   //handle content elements separately
   ContentElement contentElement = child as ContentElement;
    if (contentElement != null)
    {
      DependencyObject parent = ContentOperations.GetParent(contentElement);
        if (parent != null) return parent;

         FrameworkContentElement fce = contentElement as FrameworkContentElement;
        return fce != null ? fce.Parent : null;
     }

   //also try searching for parent in framework elements (such as DockPanel, etc)
   FrameworkElement frameworkElement = child as FrameworkElement;
   if (frameworkElement != null)
   {
      DependencyObject parent = frameworkElement.Parent;
      if (parent != null) return parent;
   }

   //if it's not a ContentElement/FrameworkElement, rely on VisualTreeHelper
   return VisualTreeHelper.GetParent(child);
}

此代码段适用于Visual或Visual3D类型的任意依赖项对象。所以,假设你需要一个对某个地方托管一个给定Button控件的Window的引用,你只需要这样:

Button myButton = ...
Window parentWindow = UIHelper.TryFindParent<Window>(myButton);

上述TryFindParent方法还可以轻松获取给定位置的项目。以下方法基于给定位置执行命中测试。如果命中测试没有返回所请求的项目(例如,树上单击的CheckBox,而您热衷于托管CheckBox的TreeViewItem),则该过程会将查找委托给TryFindParent。

如果您现在只需要鼠标指针下方的内容,这对鼠标相关事件非常方便:

  public static T TryFindFromPoint<T>(UIElement reference, Point point)
    where T:DependencyObject
  {
     DependencyObject element = reference.InputHitTest(point)
                           as DependencyObject;
     if (element == null) return null;
     else if (element is T) return (T)element;
     else return TryFindParent<T>(element);
  }

Reference