3

Considering an already loaded and rendered TabControl with three tabs, with selected tab being index 1 (the middle one):

Tab 1: Has one TextBox

Tab 2: Has two TextBoxes

Tab 3: Has three TextBoxes

If I iterate through the selectedItem's visual tree with VisualTreeHelper, I will get Two textBoxes within the TabControl's children.

I want to iterate again when the tab selection changes and access the new tab's controls. If I switch to tab index 2, I should find three textboxes using VisualTreeHelper.

The normal solution would be to subscribe to the selection changed event and go through the tree to fetch the newly shown controls. The problem is that at this moment in time, the visual tree still has the old tab, making this search worthless.

How can I intercept the moment when the new TabItem is shown and trigger my search?

I'm creating a dynamic validation engine that monitors all input controls of a given UI, even when it changes either by ContentControl template changes or TabControl selected tab changes... I hope you get the picture.

Any ideas?

VOliveira
  • 133
  • 1
  • 1
  • 6
  • Were you able to find a solution? I am facing exactly the same problem - I need to iterate the controls of the new Tab but VisualTreeHelper shows old Tab's controls in SelectionChanged event handler. – digitguy Dec 08 '12 at 09:39

2 Answers2

2

One solution is to delay the access until the tab is fully loaded using Dispatcher.BeginInvoke:

private void TabControlSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    this.Dispatcher.BeginInvoke(DispatcherPriority.Loaded,
                                (Action)(() =>
                                {
                                    // access the new tab's visual tree here
                                }));
}

Using DispatcherPriority.Loaded means the new tab will need to load before the visual tree is accessed.

Robert Macnee
  • 11,650
  • 4
  • 40
  • 35
0

The TabControl loads/unloads its items when you switch tabs, so you should be able to attach your validation on the TabItem's Loaded event.

Rachel
  • 130,264
  • 66
  • 304
  • 490
  • Are you sure TabControl loads/unloads its items so the Unloaded event of old TabItem and Loaded event of new TabItem will be raised? I tried this, but the Loaded/Unloaded event were never raised on changing tabs. – digitguy Dec 08 '12 at 09:49
  • @digitguy Do all your `TabItems` share the same `ItemTemplate`? If so, it will re-use the existing template instead of unloading and reloading a new one – Rachel Dec 08 '12 at 21:31
  • No am not using any ItemTemplate. I have a simple TabControl having two TabItems, each having its own StackPanel with couple of TextBoxes in it. – digitguy Dec 09 '12 at 10:05