GetTemplateChild

Oct 26, 2009 at 10:06 AM

I'm fairly new to WPF so please bear with me if the following is a dumb question.

I take it that GetTemplateChild is used quite extensively in the Patient Demonstrator to access e.g. "embedded" resources like storyboards found inside ContentTemplates, etc. However, this doesn't seem to work in WPF and the documentation for the WPF version of GetTemplateChild states: Do not use. Use FindName instead. The documentation also states: FindName supplies the same function as this method. FindName is public instead of protected, and it uses correct name-scoping considerations that allow it to access the template within an element and find named items within it.

The signature for FindName is (C#)

public Object FindName(string name, FrameworkElement templatedParent)

(FindName is a public method in class FrameworkTemplate).

Now imagine that we have designed some kind of special button class with no visible representation and in the XAML for e.g. a control containing our special button we provide a ContentTemplate for our button. The ContentTemplate contains a grid which again contains a resource section which again contains a StoryBoard. Now, in the code behind for the button we're interested in programatically manipulating one of the elements of the storyboard (i.e. the button expects certain named elements to be present in the storyboard). In Silverlight one would use GetTemplateChild, but in WPF this method returns 'null' even when we provide the correct element name. So, we turn to FindName like this

if (this.Template != null)
{
    var sb = (StoryBoard) Template.FindName("Checked", this);
}

After the call to FindName, sb is (still) null. Now, if I name the grid "myGrid" and call FindName like this

var g = (Grid) Template.FindName("myGrid", this);

then the element is found and g contains a reference to "myGrid".

Can anyone be kind and explain why the grid is found by FindName while an element within the storyboard isn't? (and yes, I have tried FindResource to no avail). Has it got something to do with the storyboard being a part of the grids resources?

Why is the functionality with respect to GetTemplateChild different in Silverlight? Doesn't this make porting applications from Silverlight to WPF (and vice-versa) cumbersome, to say the least?

Best regards,

norgie

Developer
Oct 27, 2009 at 3:51 PM

Hello

I'm sorry this does not address your question but if you have questions about the framework, you should post them in the appropriate Silverlight or WPF forum at:

http://forums.silverlight.net/forums/ or

http://social.msdn.microsoft.com/forums/en-US/wpf/threads/

Regards

Ben