Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically add a TextBlock to a DataTemplate

<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)
like image 948
jsj Avatar asked Oct 11 '25 08:10

jsj


1 Answers

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 do I create a datatemplate with content programmatically?

like image 116
Nikhil Agrawal Avatar answered Oct 13 '25 20:10

Nikhil Agrawal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!