如何在代码中设置控制模板? [英] How to set Control Template in code?

查看:27
本文介绍了如何在代码中设置控制模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 XAML 中有这个

I have this in XAML

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

我想在 C# 代码中实现相同的目标.我怎样才能做到这一点?

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?

推荐答案

在代码隐藏中创建模板不是一个好主意,理论上可以通过定义 ControlTemplate.VisualTree 来实现,它是一个 FrameworkElementFactory.

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;

分配属性非常迂回,因为您需要使用SetValueSetBinding:

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:

设置控制模板以编程方式就像使用XAML 因为我们必须使用XamlReader 类.

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.

根据文档FrameworkElementFactory 已弃用:

According to the documentation FrameworkElementFactory is deprecated:

该类是一种不推荐使用的以编程方式创建模板的方式,模板是 FrameworkTemplate 的子类,例如 ControlTemplate 或 DataTemplate;使用此类创建模板时,并非所有模板功能都可用.以编程方式创建模板的推荐方法是使用 XamlReader 类的 Load 方法从字符串或内存流加载 XAML.

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.

我想知道这个建议是否是个好主意.就个人而言,如果我可以避免使用字符串和 XamlReader 将模板定义为 XAML 中的资源,我仍然会继续使用.

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.

这篇关于如何在代码中设置控制模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆