2017-05-27 71 views
0

我在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; 

回答

1

它不支持在UWP中,我以前沒有找到直接設置它的方法。根據MS文檔。

的ControlTemplate:此被用作Control.Template 屬性的值,其通過將 模板定義的控制的視覺效果。 您幾乎總是使用隱式密鑰TargetType將ControlTemplate定義爲XAML 資源,該隱式密鑰TargetType與使用Setter設置Control.Template的Style 相同。您很少會在控件實例上直接爲Control.Template分配 值。

除了可能深入研究反射,或根據第一個示例使用XAMLReader,我從來沒有找到另一種方法來做到這一點,就像在WPF中做的那樣。

相關問題