从MainPage_Loaded运行时,VisualTreeHelper.GetChildrenCount返回0

Mic*_*ckD 1 silverlight windows-phone-7

在我的WP7应用程序中,我正在使用这个man方法来查找TextBlocka ToggleButton. /sf/answers/123194641/

当我在应用程序运行时拨打电话时,它可以正常工作.
如果我尝试进行完全相同的调用MainPage_Loaded,则FindChild返回null.

这是简单的电话

TextBlock myText = FindChild<TextBlock>(myToggle, "toggleTitle");  
myText.Text = "Some text";
Run Code Online (Sandbox Code Playgroud)

它看起来像是因为VisualTreeHelper.GetChildrenCount返回0.

为什么在应用程序运行时它没有值而不是从MainPage_Loaded?是不是MainPage_Loaded要等到应用程序加载才开始发射事件?

谢谢

Bry*_*ant 5

您可以使用的一个技巧是在Loaded事件上排队调用.因此,在MainPage_Loaded处理程序中将您的调用包装在Dispatcher.BeginInvoke中.

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

这将添加您对队列的调用,并在当前事件周期完成后调用它(这应该是在加载所有子项时).