I want ...">

Programmatically add a TextBlock to a DataTemplate

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

I want to make the equivalent of the above XAML programmatically (for XAML more, I just showed the corresponding bits). So far I have received:

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

So, how do I now add a TextBlock to the DataTemplate .. that is, I want to do something like:

newDataTemplate.children.Add(TextBlock)
+3
source share
1 answer
var newTextBlock = new FrameworkElementFactory(typeof(TextBlock));
newTextBlock.Name = "txt";
newTextBlock.SetBinding(TextBlock.TextProperty, new Binding("fieldA"));
DataTemplate newDataTemplate = new DataTemplate(){VisualTree = newTextBlock};

I think you should look at this question.

How to create a data file with content programmatically?

+7
source

All Articles