UWP中如何设置ControlTemplate的值

How to set the value of ControlTemplate in UWP

我在 Xamarin 项目上工作,并为我在 UWP 项目中的自定义控件制作了自定义渲染器。我找到了如何使用 xml 代码设置 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: this is used as the value of the Control.Template property, which defines the visuals of a control by applying the template. You almost always define a ControlTemplate as a XAML resource, using an implicit key TargetType that is the same as a Style that sets Control.Template with a Setter. You rarely if ever assign a value for Control.Template directly on a control instance.

除了可能深入研究反射或按照您的第一个示例使用 XAMLReader 之外,我从未找到其他方法来完成此操作,就像您在 WPF 中所做的那样。