我在 XAML 中有这个
<ControlTemplate TargetType="{x:Type Button}">
<Image ...>
</ControlTemplate>
我想在 C# 代码中实现同样的目标。我怎样才能实现这个目标?
ControlTemplate ct = new ControlTemplate();..
Image img = new Image();..
现在如何将此图像分配给控制模板?我们可以这样做还是我在这里遗漏了任何概念?
在代码隐藏中创建模板不是一个好主意,理论上可以通过定义ControlTemplate.VisualTree
这是一个FrameworkElementFactory http://msdn.microsoft.com/en-us/library/system.windows.frameworkelementfactory.aspx.
ControlTemplate template = new ControlTemplate(typeof(Button));
var image = new FrameworkElementFactory(typeof(Image));
template.VisualTree = image;
分配属性非常迂回,因为您需要使用SetValue
and SetBinding
:
image.SetValue(Image.SourceProperty, ...);
另外,关于(以前)接受的答案和引用的内容:
设置控制模板
以编程方式就像使用
XAML 因为我们必须使用
XamlReader 类。
这种说法是错误的,我们不“必须”.
如果我在运行时分配模板,我会将它们定义为资源,如果需要,我可以加载它。
Edit:根据文档FrameworkElementFactory http://msdn.microsoft.com/en-us/library/system.windows.frameworkelementfactory.aspx已弃用:
此类是一种已弃用的以编程方式创建模板的方法,模板是 FrameworkTemplate 的子类,例如 ControlTemplate 或 DataTemplate;当您使用此类创建模板时,并非所有模板功能都可用。以编程方式创建模板的推荐方法是使用 XamlReader 类的 Load 方法从字符串或内存流加载 XAML。
我想知道这个建议是否是个好主意。就我个人而言,如果我可以避免使用字符串和XamlReader
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)