Finding an ancestor of a WPF dependency object

This is a simple snippet which helps you to find a specified parent of a given WPF dependency object somewhere in its visual tree:

(Snippet updated 2009.09.14)

/// <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 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);
}
} /// <summary>
/// This method is an alternative to WPF's
/// <see cref="VisualTreeHelper.GetParent"/> method, which also
/// supports content elements. Keep in mind that for content element,
/// this method falls back to the logical tree of the element!
/// </summary>
/// <param name="child">The item to be processed.</param>
/// <returns>The submitted item's parent, if available. Otherwise
/// null.</returns>
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);
}

This snippet works with arbitrary dependency objects that are of Type Visual or Visual3D. So let’s say you need a reference to the Window that hosts a given Button control somewhere, all you need is this:

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

The above TryFindParent method also makes it easy to get an item at a given position. The method below performs a hit test based on a given position. If hit testing does not return the requested item (e.g. a clicked CheckBox on a tree, while you are keen on the TreeViewItem that hosts the CheckBox), the procedure delegates the lookup to TryFindParent.

This comes in very handy for mouse-related events if you just need to now what’s under your mouse pointer:

/// <summary>
/// Tries to locate a given item within the visual tree,
/// starting with the dependency object at a given position.
/// </summary>
/// <typeparam name="T">The type of the element to be found
/// on the visual tree of the element at the given location.</typeparam>
/// <param name="reference">The main element which is used to perform
/// hit testing.</param>
/// <param name="point">The position to be evaluated on the origin.</param>
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);
}

wpf z的更多相关文章

  1. 【Python】使用torrentParser1.03对多文件torrent的分析结果

    Your environment has been set up for using Node.js 8.5.0 (x64) and npm. C:\Users\horn1>cd C:\User ...

  2. WPF 容器的Z顺序操作

    当需要动态添加.修改.删除控件时,如果要达到最好的效果,肯定不只是把需要的控件添加到容器中,并且还需要把容器中的已有控件进行排序操作(置顶.置底.前移.后移操作).由于初次接触到wpf,所以对很多知识 ...

  3. WPF 主题切换(Z)

    using System; using System.Windows; using Assergs.Windows; namespace XMLSpy.WPF.Util{ /// <summar ...

  4. WPF三大模板简介(Z)

    WPF三大模板简介   WPF支持以下类型的模板: (1) 控件模板.控件模板可以将自定义模板应用到某一特定类型的所有控件,或是控件的某一实例.决定控件外观的是ControlTemplate,它决定了 ...

  5. C# WPF 后台调整怎样使用代码把指定控件的Z序调整到最前面呢?

    Panel.SetZIndex(rectangle1, 2); //把前台名称为rectangle1的矩形的ZIndex设置为2

  6. 年度巨献-WPF项目开发过程中WPF小知识点汇总(原创+摘抄)

    WPF中Style的使用 Styel在英文中解释为”样式“,在Web开发中,css为层叠样式表,自从.net3.0推出WPF以来,WPF也有样式一说,通过设置样式,使其WPF控件外观更加美化同时减少了 ...

  7. 【基于WPF+OneNote+Oracle的中文图片识别系统阶段总结】之篇一:WPF常用知识以及本项目设计总结

    篇一:WPF常用知识以及本项目设计总结:http://www.cnblogs.com/baiboy/p/wpf.html 篇二:基于OneNote难点突破和批量识别:http://www.cnblog ...

  8. 【基于WPF+OneNote+Oracle的中文图片识别系统阶段总结】之篇二:基于OneNote难点突破和批量识别

    篇一:WPF常用知识以及本项目设计总结:http://www.cnblogs.com/baiboy/p/wpf.html 篇二:基于OneNote难点突破和批量识别:http://www.cnblog ...

  9. 在WPF程序中打开网页:使用代理服务器并可进行JS交互

    本项目环境:使用VS2010(C#)编写的WPF程序,通过CefSharp在程序的窗体中打开网页.需要能够实现网页后台JS代码中调用的方法,从网页接收数据,并能返回数据给网页.运行程序的电脑不允许上网 ...

随机推荐

  1. 1089: [SCOI2003]严格n元树

    好久没更新了..于是节操掉尽python水过本来就水的题.. n,d=map(int, raw_input().split()) if d==0: print 1 else: f=[1] for i ...

  2. 【转载】Node.js 教程(菜鸟教程系列)

    很好的一篇教程:Node.js 教程 简单做下笔记 概述 简单的说 Node.js 就是运行在服务端的 JavaScript. Node.js 是一个基于Chrome JavaScript 运行时建立 ...

  3. USACO 6.4 Wisconsin Squares

    Wisconsin Squares It's spring in Wisconsin and time to move the yearling calves to the yearling past ...

  4. HBase集群的搭建

    HBase集群的搭建(在<HBase伪分布式安装>基础上搭建) 1 集群结构,主节点(hmaster)是hadoop0,从节点(region server)是hadoop1和hadoop2 ...

  5. Mongodb C#客户端数据关联数据,使用Linq语法进行关联

    在Mongodb C# drivers 文档 官方地址:https://docs.mongodb.com/ecosystem/drivers/csharp/ 基础的使用请参考<c# Mongod ...

  6. C# 中从网络上下载文件保存到本地文件

    下面是C#中常用的从Internet上下载文件保存到本地的一些方法,没有太多的技巧. 1.通过  WebClient  类下载文件 WebClient webClient = new WebClien ...

  7. Dijkstra算法---HDU 2544 水题(模板)

    /* 对于只会弗洛伊德的我,迪杰斯特拉有点不是很理解,后来发现这主要用于单源最短路,稍稍明白了点,不过还是很菜,这里只是用了邻接矩阵 套模板,对于邻接表暂时还,,,没做题,后续再更新.现将这题贴上,应 ...

  8. NPE是什么

    在编程中出现的空指针异常 Map类集合K/V能不能存储null值的情况,如下表格: remove元素要使用Iterator方式,如果并发操作,需要对Iterator对象加锁. Arrays.asLis ...

  9. Chrome 无痕模式

    Windows.Linux 或 Chrome 操作系统:按 Ctrl + Shift + n

  10. 机器学习之路: 初识tensorflow 第一个程序

    计算图 tensorflow是一个通过计算图的形式来表示计算的编程系统tensorflow中每一个计算都是计算图上的一个节点节点之间的边描述了计算之间的依赖关系 张量 tensor张量可以简单理解成多 ...