如何从代码在Windows Store应用创建控件模板的背后?(How to create Cont

2019-10-18 08:59发布

更新1

如果控件模板已经绑定,将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>

我搜索了很多的所有都显示FrameworkElementFactoryVisualTree的ControlTemplate的财产。 这些都不是.NET中的Windows应用商店的应用程序avaible。

任何人都知道,以创建ControlTemplate从后面的代码?

Answer 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;



Answer 2:

从这个链接是什么我得到的是控件模板是属于页面的XAML一部分,因为你不能从简单的运行时间蜜蜂改变它们。 是THR可能的方式来做到这一点,但不建议..



Answer 3:

您可以定义模板一部分你的控制,然后定义你的模板面板,你将能够检索程序。

[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>


文章来源: How to create ControlTemplate from code behind in Windows Store App?