首页 文章

如何在UWP中设置ControlTemplate的值

提问于
浏览
0

我正在研究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;

1 回答

  • 1

    它在UWP中不受支持,我以前发现无法直接设置它 . 根据MS文档 .

    ControlTemplate:它用作Control.Template属性的值,该属性通过应用模板定义控件的视觉效果 . 您几乎总是将ControlTemplate定义为XAML资源,使用隐式键TargetType与使用Setter设置Control.Template的Style相同 . 您很少直接在控件实例上为Control.Template分配值 .

    除了可能深入研究反射,或者根据你的第一个例子使用XAMLReader之外,我从未找到另一种方法来实现它,就像你在WPF中那样 .

相关问题