以编程方式将TextBlock添加到DataTemplate

jsj*_*jsj 3 c# wpf xaml datatemplate

<DataTemplate>
    <TextBlock x:Name="Txt" Text="{Binding fieldA}" />
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)

我想以编程方式完成相应的上述XAML(XAML还有更多,我只显示了相关的位).到目前为止我有:

DataTemplate newDataTemplate = new DataTemplate();
TextBlock newTextBlock = new TextBlock();
newTextBlock.SetBinding(TextBlock.TextProperty, new Binding("fieldA"));
newTextBlock.Name = "txt";
Run Code Online (Sandbox Code Playgroud)

那么我现在如何将TextBlock添加到DataTemplate ...即我想做类似的事情:

newDataTemplate.children.Add(TextBlock)
Run Code Online (Sandbox Code Playgroud)

Nik*_*wal 7

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

我想你应该看看这个问题.

如何以编程方式创建包含内容的datatemplate?