How to create ControlTemplate from code behind in Windows Store App?

只谈情不闲聊 提交于 2019-12-13 04:14:38

问题


UPDATE 1

If ControlTemplate has binding, will XamlReader.Load(...) work ?

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

I want to achieve this from code behind.

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

I searched a lot all are showing FrameworkElementFactory & VisualTree property of ControlTemplate. These are not avaible in .NET for Windows Store Apps.

Anyone knows to create ControlTemplate from code behind ?


回答1:


Try this:

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

May be there is a more beautiful solution, but this sample works.

add: Don't forget include Windows.UI.Xaml.Markup namespace: using Windows.UI.Xaml.Markup;




回答2:


from this link what i am getting is that controltemplate is belong to xaml part of the page because you can not alter them from simple run time Apis . yes thr may be way to do that but it is not recommended..




回答3:


You can define a Template part for your control, and then define a panel in your Template that you will be able to retrieve programmatically.

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


来源:https://stackoverflow.com/questions/17593999/how-to-create-controltemplate-from-code-behind-in-windows-store-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!