0

更新 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 for Windows Store Apps 中不可用。

有人知道ControlTemplate从后面的代码创建吗?

4

3 回答 3

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;

于 2013-07-11T13:44:14.900 回答
0

这个链接我得到的是 controltemplate 属于页面的 xaml 部分,因为您无法从简单的运行时 APIs 更改它们。是的 thr 可能是这样做的方法,但不推荐..

于 2013-07-11T13:42:11.933 回答
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>
于 2013-07-12T13:18:09.723 回答