views:

471

answers:

1

I'm writing a custom control which uses a template defined in the resources section of my XAML and I'd like to replace one or more template parts in an instance of my control at runtime.

For example, if I have a part named "ActivePart" in the control's template, how do I replace the ActivePart's FrameworkElement in an instance of the control with a new FrameworkElement?

I realise the Control.Template property is writeable, but I'd prefer to find a way to replace a specific part of that template rather than create a whole new one, although a solution that edits the existing template by replacing the appropriate named part would be acceptable.

I'm using C# and need to do this at runtime using any FrameworkElement, so I'm not looking for XAML-based solutions or suggestions, thanks!

P.S. I'm aware that GetTemplateChild() returns the FrameworkElement for a named template part in a control instance, but I don't see how that helps me to replace that part with a new FrameworkElement.

A: 

I guess I was missing the obvious!

After OnApplyTemplate is called on your derived Control, VisualTreeHelper.GetChild (this, 0) will return the root object of the instantiated template's visual tree, from which you can use the Children collection (if your Control's template is Panel-derived, e.g. Canvas, Grid, etc.) to add/remove/modify any of the child template parts to your heart's content.

Before OnApplyTemplate is called, no visual tree exists for the Control, and VisualTreeHelper.GetChildrenCount returns 0.

Duckboy