Wpf关于以编程方式提升控制树的问题 [英] Wpf question about programmatically moving up the control tree

查看:66
本文介绍了Wpf关于以编程方式提升控制树的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

必须有一个比这更好的方法:



var tabItem =(TabItem)((ContentControl)((UserControl) ((网格)((TextBox)发送者).Parent).Parent).Parent).Parent;



这里的想法是我需要获取TextBox所在的TabItem,它位于一个网格中,位于用户控件中,位于TabItem的ContentControl中。



我尝试了什么:



由于问题状态(但我需要30个字符),这个:



var tabItem =(TabItem)((ContentControl)((UserControl)((Grid)((TextBox)sender).Parent).Parent).Parent).Parent;



是粗略的并且取决于控制树结构。

There has got to be a better way than this:

var tabItem = (TabItem)((ContentControl)((UserControl)((Grid)((TextBox)sender).Parent).Parent).Parent).Parent;

The idea here is that I need to get the TabItem in which the TextBox resides, which is in a grid, which in a user control, which is in the TabItem's ContentControl.

What I have tried:

As the "problem" states (but I need 30 characters here), this:

var tabItem = (TabItem)((ContentControl)((UserControl)((Grid)((TextBox)sender).Parent).Parent).Parent).Parent;

is gross and dependent on the control tree structure.

推荐答案

System.Windows.Media namespace具有 VisualTreeHelper 类,您可以使用<$ c $遍历依赖树c> GetChild 和 GetParent 方法。



所以你可以这样做(未经测试):

System.Windows.Media namespace has the VisualTreeHelper class that you can use to traverse the dependancy tree using GetChild and GetParent methods.

So you could do something like this (untested):
private FrameworkElement GetParent(FrameworkElement item, Type targetType)
{
    var parent = VisualTreeHelper.GetParent(item);
    while (parent.GetType() != targetType)
    {
        parent = VisualTreeHelper.GetParent(parent);
    }
    return parent;
}

然后使用将是(未经测试):

Then to use would be (untested):

var tabItem = GetParent(sender as FrameworkElement, TabItem);


这篇关于Wpf关于以编程方式提升控制树的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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