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. CF 586A 找1的个数和101的个数

    Sample test(s) input 50 1 0 1 1 output 4 input 71 0 1 0 0 1 0 output 4 input 10 output 0 # include & ...

  2. 【58沈剑架构系列】为什么说要搞定微服务架构,先搞定RPC框架?

    第一章聊了[“为什么要进行服务化,服务化究竟解决什么问题”] 第二章聊了[“微服务的服务粒度选型”] 今天开始聊一些微服务的实践,第一块,RPC框架的原理及实践,为什么说要搞定微服务架构,先搞定RPC ...

  3. Session机制三(表单的重复提交)

    1.表单的重复提交的情况 在表单提交到一个servlet,而servlet又通过请求转发的方式响应了一个JSP页面,这个时候地址栏还保留这servlet的那个路径,在响应页面点击刷新. 在响应页面没有 ...

  4. CentOS 使用命令设置代理

    全局的代理设置, vim /etc/profile 添加下面内容 http_proxy = http://username:password@yourproxy:8080/ ftp_proxy = h ...

  5. 自然语言处理系列-1.什么是NLP?

    常常会听到有人说,自然语言处理(NLP)是人工智能技术(AI)皇冠上的明珠.那么,从这句话上就能够看到,目前我们常常说的NLP其实是AI技术的一个分支,而且是较难的那一个分支. 那么,到底什么是NLP ...

  6. 初识Spring——Spring核心容器

    一. IOC和DI基础 IOC-Inversion of Control,译为控制反转,是一种遵循依赖倒置原则的代码设计思想. 所谓依赖倒置,就是把原本的高层建筑依赖底层建筑“倒置”过来,变成底层建筑 ...

  7. Oracle win32_11gR2_client.zip

    先将下载下来的ZIP文件解压,并运行setup.exe文件. 第一步:选择管理员(0MB)(A),然后点击下一步 第二步:选择语言,点击下一步 第三步:选择安装的路径,然后点击下一步 第四步:执行到第 ...

  8. [leetcode tree]100. Same Tree

    判断输入的两棵树是不是相同 判断当前root值,左子树和右子树是否相同 ####注意最后用的是 is 而不是 ==,因为最后判断p和q是不是None, 应该判断是不是同一个对象 class Solut ...

  9. spring4声明式事务—02 xml配置方式

    1.配置普通的 controller,service ,dao 的bean. <!-- 配置 dao ,service --> <bean id="bookShopDao& ...

  10. Openstack-开发基础 stevedore学习

    在给openstack-N版加路由的时候发现怎么都无法搞定,原来现在用这个模块来处理了 stevedore是用来实现动态加载代码的开源模块.它是在OpenStack中用来加载插件的公共模块.可以独立于 ...