Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is a a ControlTemplate instantiated in XAML?

In code a ControlTemplate contains a hierarchy of FrameworkElementFactory that can be used to construct the framework elements themselves. But, in XAML, a ControlTemplate's content appears as the elements themselves.

Does the XAML parser convert from one object form to the other, is a ValueConverter used, or does it actually create the factories as it parses the ControlTemplate content?

like image 206
mancaus Avatar asked Dec 09 '25 13:12

mancaus


1 Answers

It is actually done differently, if it's defined in XAML versus in code. To verify, you can create a simple project in WPF with a single Window and add a custom Control that has a ControlTemplate defined in XAML by it's default Style. Then add the control to your window and add a Button, whose Click handler includes a breakpoint.

When the breakpoint is hit, we can inspect the custom control and it's ControlTemplate. The VisualTree property (which is FrameworkElementFactory) is null.

Using Reflector, we can see the relevant code in the StyleHelper.ApplyTemplateContent method. The first if-statement in that method, applies a FrameworkElementFactory (which is passed in from the VisualTreeProperty). The second if-statement loads the ControlTemplate from XAML, which ultimately executes FrameworkTEmplate.LoadOptimizedTemplateContent.

like image 151
CodeNaked Avatar answered Dec 12 '25 07:12

CodeNaked



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!