3
<DataTemplate>
    <TextBlock x:Name="Txt" Text="{Binding fieldA}" />
</DataTemplate>

I want to do the equivalent of the above XAML programatically (There is more to the XAML, I have only shown the relevant bits). So far I have got:

DataTemplate newDataTemplate = new DataTemplate();
TextBlock newTextBlock = new TextBlock();
newTextBlock.SetBinding(TextBlock.TextProperty, new Binding("fieldA"));
newTextBlock.Name = "txt";

So how do I now add the TextBlock to the DataTemplate.. i.e. I want to do something like:

newDataTemplate.children.Add(TextBlock)
4

1 回答 1

7
var newTextBlock = new FrameworkElementFactory(typeof(TextBlock));
newTextBlock.Name = "txt";
newTextBlock.SetBinding(TextBlock.TextProperty, new Binding("fieldA"));
DataTemplate newDataTemplate = new DataTemplate(){VisualTree = newTextBlock};

我认为你应该看看这个问题。

如何以编程方式创建包含内容的数据模板?

于 2012-04-29T06:27:42.107 回答