How do I replace a ControlTemplate part at runtime, in Silverlight 3?

╄→гoц情女王★ 提交于 2020-01-06 01:52:07

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/2036879/how-do-i-replace-a-controltemplate-part-at-runtime-in-silverlight-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!