【转自 : Windows Phone Developer Network】关于WP7 中页面元素生成 加载顺序的简单分析解决思路

【转自 : Windows Phone Developer Network】关于WP7 中页面元素生成 加载顺序的简单分析
转自: Windows Phone Developer Network

在写代码时 我们通常会关心 页面中各个控件的加载顺序,现在我们来做一个简单分析 

我们先创建一个WP 应用程序 Phone App2  

我们先重写 3个控件 Grid、StackPlane、Button 并在构造函数中添加输出一条debug 信息
public class CustomGrid : System.Windows.Controls.Grid
  {
  public CustomGrid()
  :base()
  {
  System.Diagnostics.Debug.WriteLine("Structure Grid");
  }

   
  }

  public class CustomStackPanel: System.Windows.Controls.StackPanel
  {
  public CustomStackPanel()
  : base()
  {
  System.Diagnostics.Debug.WriteLine("Structure StackPanel");
   
   

  }


  }


  public class CustomButton:Button
  {
  public CustomButton()
  : base()
  {
  System.Diagnostics.Debug.WriteLine("Structure Button");

  }
  }
复制代码
然后我们在MainPage 中添加如下界面布局 ,大家注意到 这个布局是用的是我们刚才定制的空间 并且 这是一个嵌套的布局
  <c:CustomGrid x:Name="LayoutRoot" Background="Transparent" Loaded="LayoutRoot_Loaded" Unloaded="LayoutRoot_Unloaded">
  <c:CustomStackPanel x:Name="panle" Loaded="StackPanel_Loaded" Unloaded="CustomStackPanel_Unloaded">

  <c:CustomButton x:Name="button" Content="Button" Loaded="CustomButton_Loaded" Unloaded="CustomButton_Unloaded" Click="button_Click"></c:CustomButton>
  </c:CustomStackPanel>
  </c:CustomGrid>
复制代码
接下来我们 分别为这3个控件 写loaded 和 unloaded 方法 同样在里面输出一条 Debug信息
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
  {
  System.Diagnostics.Debug.WriteLine("Page Loaded");

  }

  private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
  {
  System.Diagnostics.Debug.WriteLine("LayoutRoot Loaded");

  }

  private void StackPanel_Loaded(object sender, RoutedEventArgs e)
  {
  System.Diagnostics.Debug.WriteLine("Panle Loaded");

  }

  private void CustomButton_Loaded(object sender, RoutedEventArgs e)
  {
  System.Diagnostics.Debug.WriteLine("button Loaded");

  }

  private void PhoneApplicationPage_Unloaded(object sender, RoutedEventArgs e)
  {
  System.Diagnostics.Debug.WriteLine("Page UnLoaded");

  }

  private void LayoutRoot_Unloaded(object sender, RoutedEventArgs e)
  {
  System.Diagnostics.Debug.WriteLine("LayoutRoot UnLoaded");

  }

  private void CustomStackPanel_Unloaded(object sender, RoutedEventArgs e)
  {
  System.Diagnostics.Debug.WriteLine("Panle UnLoaded");

  }

  private void CustomButton_Unloaded(object sender, RoutedEventArgs e)
  {
  System.Diagnostics.Debug.WriteLine("button UnLoaded");

  }
复制代码
重写 Nav To 和 Nav From 在里面输出debug 信息
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
  {