2

I'm very new to WPF and don't know how to do this. I have a text box in a tab item on a tab control. How can I programmatically (C#) determine what tab item is the parent of this text box? I would also like to determine what tab control is the parent of the tab item.

Thanks very much.

Hosea146
  • 7,412
  • 21
  • 60
  • 81

4 Answers4

9

TabItem.Parent will provide the logical parent element of the TabItem; which will be the associated TabControl. You can use the same approach for any control with the TabItem.

((FrameworkElement)myTextBox.Parent).Parent;

If the item is deeper in the tree and becomes unknown in its depth you will need to begin to approach it in a recursive manner.

Aaron McIver
  • 24,527
  • 5
  • 59
  • 88
2

You can use FrameworkElement.Parent to walk up the hierarchy of a control in WPF. This should let you (recursively) walk up until you find the TabItem, then walk up to the TabControl from there.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
1

I am newbie in WPF too, but what about cycle searching? For example:

TextBox TB = new TextBox();
TabControl MyTabControl = new TabControl();
// ...
foreach (TabItem ti in MyTabControl.Items)
   if (TB.Parent == ti)
   {
      // textbox is here!
      MessageBox.Show(ti.ToString());
      break;
   }
Dmitriy
  • 654
  • 10
  • 24
0

Here is a generic method for finding parent controls: How can I find WPF controls by name or type?

You can call it like this:

TabItem owner = UIHelper.FindVisualParent<TabItem>(myTextBox);
Community
  • 1
  • 1
John Myczek
  • 12,076
  • 4
  • 31
  • 44