none
GetTemplateChild returns null RRS feed

  • Question

  • I have a controller with the following pieces:

    controller.generic.xaml

    <!-- MENU BAR -->
    <StackPanel x:Name="FileMenuBarContent" Grid.Row="2" Grid.ColumnSpan="2">
      <!-- Content will be injected at runtime -->
    </StackPanel>


    controller.cs

    [TemplatePart(Name = "FileMenuBarContent", Type = typeof(StackPanel))]



    When I call GetTemplateChild("FileMenuBarContent") from my view it returns the appropriate DependencyObject but when it's called a second time from a different view it returns null. Both views inherit from the controller class. Does anyone have an explanation for this?

    Thanks in advance.
    Tuesday, November 6, 2007 11:28 PM

Answers

  •    GetTemplateChild() can only be safely called after the template is expanded. You'd better override OnApplyTemplate() method, and call GetTemplateChild() in that method.

     

       Hope this helps

    Thursday, November 8, 2007 7:18 AM

All replies

  •    GetTemplateChild() can only be safely called after the template is expanded. You'd better override OnApplyTemplate() method, and call GetTemplateChild() in that method.

     

       Hope this helps

    Thursday, November 8, 2007 7:18 AM
  • private static void OnPopupPositionOriginChangedCallback(DependencyObject source, DependencyPropertyChangedEventArgs args)
    {
      DTPopupPushpin pushpin = (DTPopupPushpin)source;
      DTPositionOrigin newPositionOrigin = (DTPositionOrigin)args.NewValue;
    
      Border popup = pushpin.GetTemplateChild("Popup") as Border;
      if (popup != null)
      {
        switch (newPositionOrigin)
        {
          case DTPositionOrigin.TopLeft:
            popup.SetValue(Grid.RowProperty, 0);
            popup.SetValue(Grid.ColumnProperty, 0);
            break;
    
    
    I'm not sure I'm doing this correctly, but what I have is a control derived from ContentControl and on this control I wanted to make a dependency property called PopupPositionOrigin with a callback function that will rearrange a few content elements according to the value the property is set.  Above is how I thought I could program the callback, however, pushpin.GetTemplateChild("Popup") is null because, I assume, the ContentTemplate has not yet been applied.  Do I have the wrong approach?  What should I do?
    Friday, August 13, 2010 4:23 AM