MickD
MickD

Reputation: 45

VisualTreeHelper.GetChildrenCount returns 0 when run from MainPage_Loaded

In my WP7 app, I'm using this guys method to find a TextBlock within a ToggleButton. https://stackoverflow.com/a/1759923/1339857

When I make the call while the app is running it works fine.
If I try and make the exact same call from MainPage_Loaded, FindChild returns null.

Here's the simple call

TextBlock myText = FindChild<TextBlock>(myToggle, "toggleTitle");  
myText.Text = "Some text";

It looks like it's because VisualTreeHelper.GetChildrenCount is returning 0.

Why would it have a value when the app is running but not from MainPage_Loaded? Is'nt the purpose of MainPage_Loaded to wait until the app is loaded before firing off events?

Thanks

Upvotes: 1

Views: 551

Answers (1)

Bryant
Bryant

Reputation: 8670

One trick you can use to deal with this is to queue up your call on the Loaded event. So in the MainPage_Loaded handler wrap your call in a Dispatcher.BeginInvoke.

Dispatcher.BeginInvoke(() => {
  TextBlock myText = FindChild<TextBlock>(myToggle, "toggleTitle");  
  myText.Text = "Some text";
}

This will add your call to the queue and it will get called after the current event cycle has completed (which should be when all the child items have been loaded).

Upvotes: 5

Related Questions