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!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…