0

更新1如何從Windows Store App中的代碼創建ControlTemplate?

如果控件模板已經綁定,將XamlReader.Load(...)工作?

<ControlTemplate TargetType="charting:LineDataPoint"> 
    <Grid> 
     <ToolTipService.ToolTip> 
      <ContentControl Content="{Binding Value,Converter={StaticResource DateToString},ConverterParameter=TEST}"/> 
     </ToolTipService.ToolTip> 
     <Ellipse Fill="Lime" Stroke="Lime" StrokeThickness="3" /> 
    </Grid> 
</ControlTemplate> 

我想從後面的代碼實現這一目標。

<ControlTemplate> 
    <Ellipse Fill="Green" Stroke="Red" StrokeThickness="3" /> 
</ControlTemplate> 

我搜索了很多的所有都顯示的ControlTemplate FrameworkElementFactory & VisualTree財產。這些不適用於Windows應用商店的.NET。

任何人都知道從代碼背後創建ControlTemplate

回答

0

this鏈接我得到的是,controltemplate屬於頁面的xaml部分,因爲你不能從簡單的運行時間Apis中改變它們。是THR可能的方式來做到這一點,但不建議..

1

試試這個:

private static ControlTemplate CreateTemplate() 
    { 
     const string xaml = "<ControlTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><Ellipse Fill=\"Green\" Stroke=\"Red\" StrokeThickness=\"3\" /></ControlTemplate>"; 
     var сt = (ControlTemplate)XamlReader.Load(xaml); 
     return сt; 
    } 

可能有一個更漂亮的解決方案,但這個樣本的作品。

添加:不要忘記包括Windows.UI.Xaml.Markup命名空間: using Windows.UI.Xaml.Markup;

+0

我已經知道這個解決方案。 – Xyroid

+0

我的控件模板也有綁定,會起作用嗎?查看相關更新。 – Xyroid

0

您可以爲您的控制模板部分,然後定義你的模板面板,你將能夠以編程方式檢索。

[TemplatePart(Name = "RootPanel", Type = typeof(Panel))] 
public class TestControl : Control 
{ 
    private Panel panel; 
    protected override void OnApplyTemplate() 
    { 
     base.OnApplyTemplate(); 
     panel = (Panel) GetTemplateChild("RootPanel"); 
     panel.Children.Add(new Ellipse() 
     { 
      Fill = new SolidColorBrush(Colors.Green), 
      Stroke = new SolidColorBrush(Colors.Red), 
      StrokeThickness = 3, 
      VerticalAlignment =VerticalAlignment.Stretch, 
      HorizontalAlignment = HorizontalAlignment.Stretch 
     }); 
    } 
} 

<ControlTemplate TargetType="local:TestControl"> 
     <Grid x:Name="RootPanel" /> 
</ControlTemplate> 
相關問題