我正在研究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;
答案 0 :(得分:1)
UWP不支持,之前我发现无法直接设置它。根据MS文档。
ControlTemplate:它用作Control.Template的值 property,通过应用来定义控件的视觉效果 模板。 您几乎总是将ControlTemplate定义为XAML 资源,使用与Style相同的隐式键TargetType 使用Setter设置Control.Template。你很少分配一个 Control.Template的值直接在控件实例上。
除了可能深入研究反射,或者根据你的第一个例子使用XAMLReader之外,我还没有找到另一种方法来实现它,就像你在WPF中那样。