Click here to Skip to main content
15,885,182 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.
Posted
Updated 26-Mar-17 14:56pm
Comments
Marco Bertschi 27-Mar-17 5:39am    
"I need 30 characters here"
Never did myself.

1 solution

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):
C#
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):
C#
var tabItem = GetParent(sender as FrameworkElement, TabItem);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900