The TabControl in Silverlight has some interesting behaviors. One of those behaviors is that since Silverlight does not have a Logical Tree and only has a Visual Tree, controls that are inside a tab that is not visible will not appear in the visual tree. If this sounds foreign to you, don’t worry.

To see this in action, here is a simple Silverlight application:

This application has a single TabControl with two tabs. Each tab has a TextBlock inside it. This is the application as it’s running:

image

When either button is clicked, the code will walk the visual tree. The entire codebehind for this code follows:

Each button click calls a recursive function which walks the visual tree until it gets to a root parent element, then displays the path using a MessageBox. Simple enough, what happens when you have “Tab 1” active and click the first button?

image

Great! Exactly as expected. What happens when you have “Tab 2” active and click the second button?

image

Also exactly as expected. Now that “Tab 2” is selected, what happens if you click the first button?

image

Now that’s strange, isn’t it? The TextBlock is inside the TabItem, which is inside the TabControl, and so on, but Silverlight is saying the TextBlock doesn’t have any parent elements.

Why? Because anything inside a TabItem that is not the active TabItem are not in the visual tree.

What kind of side effects does this have? Well, one side effect is that every time the tab is activated the TextBlock Loaded event is raised. To see this in action, we’ll attach an event handler to the Load event:

And in codebehind, we’ll update the Text of the TextBlock every time the Loaded event is raised.

Once the application opens, we can see the time in the TextBlock loaded:

image

And if we switch to Tab 2, then back to Tab 1:

image

The Loaded event fired again, as evidenced by the text of the TextBlock changing.

What does this all mean then? If a control has some sort of behavior it runs on load, assuming that it will only be loaded a single time, theoretically it could have an unwanted consequence.

See part 2 for an example of just such an unwanted consequence.