如何在UWP中设置ControlTemplate的值
问题描述:
我在Xamarin项目中工作,并为UWP项目中的自定义控件制作自定义渲染器。我发现如何使用xml代码设置ControlTemplate。如何在UWP中设置ControlTemplate的值
XML方式:
var tb = new TextBox(); // or what I do in Xamarin var tb = Control;
var ct = (Controls.ControlTemplate)XamlReader.Load(@"
<ControlTemplate TargetType=""TextBox"" xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Grid>
....
</Grid>
</ControlTemplate>");
tb.Template = ct;
但我可怎么办代码一样吗?
var tb = new TextBox(); // or what I do in Xamarin var tb = Control;
var ct = new ControlTemplate();
ct.TargetType = typeof(TextBox);
var grid = new Grid();
ct.VisualTree = grid // This is how it was done in wpf but there is no such option in UWP
tb.Template = ct;
答
它不支持在UWP中,我以前没有找到直接设置它的方法。根据MS文档。
的ControlTemplate:此被用作Control.Template 属性的值,其通过将 模板定义的控制的视觉效果。 您几乎总是使用隐式密钥TargetType将ControlTemplate定义为XAML 资源,该隐式密钥TargetType与使用Setter设置Control.Template的Style 相同。您很少会在控件实例上直接为Control.Template分配 值。
除了可能深入研究反射,或根据第一个示例使用XAMLReader,我从来没有找到另一种方法来做到这一点,就像在WPF中做的那样。