Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...