在code创建的DataTemplate背后 [英] Create DataTemplate in code behind
问题描述
我如何添加控件编程的DataTemplates?
How do i add controls to datatemplates programmatically?
例如。下面,我创建的TextBlock和DataTemplate的。
For Example. Below I've created TextBlock and DataTemplate.
TextBlock text = new TextBlock();
DataTemplate template = new DataTemplate();
现在我需要的TextBlock添加的DataTemplate。如何实现这一目标?
Now I need to add TextBlock to DataTemplate. How to achieve this?
我知道,有在code后面addind数据模板的其他方式
1.创建XAML数据模板和加载它在code背后
2.创建并添加使用XamlParser
I know that there are other ways of addind data template in code behind 1. create a data template in XAML and load it on code behind 2. create and add using XamlParser
但我需要的方式我例子显示做。
but i need to do in the way i showed in example.
需要一些帮助。
推荐答案
您必须首先声明一个DataTemplate:
You have first to declare a DataTemplate:
DataTemplate template = new DataTemplate { DataType = typeof(< Type of the object the template refers>) };
然后用这种方式宣告像StackPanel的布局面板
Then declare a layout panel like StackPanel in this way
FrameworkElementFactory stackPanelFactory = new FrameworkElementFactory(typeof(StackPanel));
stackPanelFactory.SetValue(StackPanel.OrientationProperty, Orientation.Vertical);
和最后附上文本块片吧:
and finally attach the TextBlock piece at it:
FrameworkElementFactory title = new FrameworkElementFactory(typeof(TextBlock));
title.SetBinding(TextBlock.TextProperty, new Binding("< name of your binding >"));
stackPanelFactory.AppendChild(title);
为了显示以这种方式,你必须把它连接到的VisualTree创建的StackPanel的:
in order to display the StackPanel created in this way you have to attach it to the VisualTree:
template.VisualTree = stackPanelFactory;
希望它帮助! :)
Hope it helps! :)
这篇关于在code创建的DataTemplate背后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!