Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

wpf - How do I create a datatemplate with content programmatically?

I want to do the following at runtime in code:

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

So far I've got:

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

    return dataTemplate;
}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

XAML:

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

Somewhere in your code:

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

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

Hope this helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...