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

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

问题描述

我有这个在XAML

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

我要实现在C#code相同。我怎样才能做到这一点?

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?

推荐答案

在codebehind创建模板是不是一个好主意,在理论上人们会通过定义做到这一点ControlTemplate.VisualTree 这是一个<一个href=\"http://msdn.microsoft.com/en-us/library/system.windows.frameworkelementfactory.aspx\"><$c$c>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;

分配属性是非常迂回的,因为你需要使用的SetValue SetBinding

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

此外,关于接受(pviously $ P $)的答案,并引述东西:

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

设置的ControlTemplate
  编程就像使用
  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.

编辑:根据该文件<一个href=\"http://msdn.microsoft.com/en-us/library/system.windows.frameworkelementfactory.aspx\"><$c$c>FrameworkElementFactory德是precated:

According to the documentation FrameworkElementFactory is deprecated:

这类是德precated以编程方式创建模板,这是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.

不知这建议是一个好主意。我个人仍然定义模板在XAML资源走,如果我能避免字符串和做它 XamlReader

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.

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

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