问题描述
必须有一个比这更好的方法:
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.
推荐答案
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关于以编程方式提升控制树的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!