如何以编程方式创建带有内容的数据模板? [英] How do I create a datatemplate with content programmatically?

查看:85
本文介绍了如何以编程方式创建带有内容的数据模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在代码运行时执行以下操作:

I want to do the following at runtime in code:

<DataTemplate x:Key="lightGreenRectangle">
        <Rectangle Fill="LightGreen"/>
    </DataTemplate>

到目前为止,我已经:

public DataTemplate GetColouredRectangleInDataTemplate(Color colour)
{
    DataTemplate dataTemplate = new dataTemplate();

    return dataTemplate;
}

帮助吗?我知道这不是设计控件样式的最优雅的方法,但是我要为其指定颜色的组件具有名为DataTemplate类型的 PointTemplate属性。

Help? I know this isn't the most elegant way of styling a control, but the component I want to specify a colour for has a property called "PointTemplate" of type DataTemplate.

推荐答案

如果出于任何原因需要以编程方式创建 DataTemplate ,则可以执行以下操作:

If for whatever reason you need to create a DataTemplate programmatically you would do:

XAML:

<Grid x:Name="myGrid">
    <ContentControl ContentTemplate="{DynamicResource lightGreenRectangle}" />
</Grid>

代码中的某处:

    public static DataTemplate CreateRectangleDataTemplate()
    {
        var rectangleFactory = new FrameworkElementFactory(typeof(Rectangle));
        rectangleFactory.SetValue(Shape.FillProperty, new SolidColorBrush(System.Windows.Media.Colors.LightGreen));

        return new DataTemplate
                   {
                       VisualTree = rectangleFactory,
                   };
    }

    public static void AddRectangleTemplateToResources(FrameworkElement element)
    {
        element.Resources.Add("lightGreenRectangle", CreateRectangleDataTemplate());
    }

然后,您只需要添加 DataTemplate ResourceDictionary 以便可以使用。例如,在后面的代码中:

Then you just need to add the DataTemplate to a ResourceDictionary so it can be used. For example, in the code behind:

    public MainWindow()
    {
        InitializeComponent();
        AddRectangleTemplateToResources(myGrid);
    }

希望这会有所帮助!

这篇关于如何以编程方式创建带有内容的数据模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆