Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Control Template in code?

I have this in XAML

<ControlTemplate TargetType="{x:Type Button}">     <Image ...> </ControlTemplate> 

I want to achieve same in C# code. How can I achieve this?

ControlTemplate ct = new ControlTemplate();.. Image img = new Image();.. 

Now how to assign this Image to Control template? Can we do this or Am I missing any concept here?

like image 774
Haris Hasan Avatar asked Apr 22 '11 12:04

Haris Hasan


People also ask

What is a control template?

The ControlTemplate allows you to specify the visual structure of a control. The control author can define the default ControlTemplate and the application author can override the ControlTemplate to reconstruct the visual structure of the control.

Where do you put ControlTemplate?

The most common way to declare a ControlTemplate is as a resource in the Resources section in a XAML file. Because templates are resources, they obey the same scoping rules that apply to all resources. Put simply, where you declare a template affects where the template can be applied.

What is the difference between control template and data template?

A ControlTemplate will generally only contain TemplateBinding expressions, binding back to the properties on the control itself, while a DataTemplate will contain standard Binding expressions, binding to the properties of its DataContext (the business/domain object or view model).


1 Answers

Creating template in codebehind is not a good idea, in theory one would do this by defining the ControlTemplate.VisualTree which is a FrameworkElementFactory.

ControlTemplate template = new ControlTemplate(typeof(Button)); var image = new FrameworkElementFactory(typeof(Image)); template.VisualTree = image; 

Assigning properties is very roundabout since you need to use SetValue and SetBinding:

image.SetValue(Image.SourceProperty, ...); 

Also, about the (previously) accepted answer and the stuff quoted:

Setting the ControlTemplate programmatically is just like using XAML because we have to use the XamlReader class.

That statement is just wrong, we do not "have to".


If i assign templates at run time i define them as a resource which i can load if i need it.


Edit: According to the documentation FrameworkElementFactory is deprecated:

This class is a deprecated way to programmatically create templates, which are subclasses of FrameworkTemplate such as ControlTemplate or DataTemplate; not all of the template functionality is available when you create a template using this class. The recommended way to programmatically create a template is to load XAML from a string or a memory stream using the Load method of the XamlReader class.

I wonder if this recommendation is such a good idea. Personally i would still go with defining the template as a resource in XAML if i can avoid doing it with strings and the XamlReader.

like image 59
H.B. Avatar answered Sep 28 '22 07:09

H.B.