4
<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)
H.B.
  • 166,899
  • 29
  • 327
  • 400
jsj
  • 9,019
  • 17
  • 58
  • 103

1 Answers1

7
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?

Community
  • 1
  • 1
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
  • this isn't working.. the TextBlock never makes it to the DataTemplate's tree surely there is a way to just slap the TextBlock into the DataTemplate's tree. – jsj Apr 29 '12 at 06:55
  • 1
    @trideceth12: By the way, [this is deprecated](http://msdn.microsoft.com/en-us/library/system.windows.frameworkelementfactory.aspx). – H.B. Jul 23 '12 at 04:53