Xaml 如何从Windows应用商店应用程序中的代码隐藏创建ControlTemplate?

Xaml 如何从Windows应用商店应用程序中的代码隐藏创建ControlTemplate?,xaml,windows-8,windows-runtime,microsoft-metro,controltemplate,Xaml,Windows 8,Windows Runtime,Microsoft Metro,Controltemplate,更新1 如果ControlTemplate有绑定,XamlReader.Load(…)会工作吗 <ControlTemplate TargetType="charting:LineDataPoint"> <Grid> <ToolTipService.ToolTip> <ContentControl Content="{Binding Value,Converter={StaticResource DateT

更新1

如果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
属性。这些在.NET Windows应用商店应用程序中不可用

任何人都知道如何从代码隐藏中创建
ControlTemplate

从链接中我得到的是,ControlTemplate属于页面的xaml部分,因为您无法从简单的运行时API中更改它们。是的,这可能是一种方法,但不建议这样做。

尝试以下方法:

    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;
    }
private static ControlTemplate CreateTemplate()
{
常量字符串xaml=“”;
varСt=(ControlTemplate)XamlReader.Load(xaml);
返回Сt;
}
也许有一个更漂亮的解决方案,但这个示例很有效

添加:不要忘记包含Windows.UI.Xaml.Markup命名空间:

使用Windows.UI.Xaml.Markup;

您可以为控件定义一个模板部件,然后在模板中定义一个可以通过编程方式检索的面板

[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>
[TemplatePart(Name=“RootPanel”,Type=typeof(Panel))]
公共类TestControl:Control
{
私人事务委员会;
受保护的覆盖无效OnApplyTemplate()
{
base.OnApplyTemplate();
panel=(panel)GetTemplateChild(“根面板”);
panel.Children.Add(新椭圆()
{
填充=新的SolidColorBrush(颜色为绿色),
笔划=新的SolidColorBrush(颜色为红色),
冲程厚度=3,
VerticalAlignment=VerticalAlignment.Stretch,
水平对齐=水平对齐。拉伸
});
}
}

我的控件模板也有绑定功能,可以使用吗?请参阅相关更新。