tags:

views:

669

answers:

3

How can I convert this XAML code into C# code?

<Window.Resources>
    <DataTemplate x:Key="itemtemplate">
        <TextBlock Text="{Binding Path=Text}"/>
    </DataTemplate>
</Window.Resources>
+1  A: 

The correct way to create DataTemplates from C# is to use a XamlReader and give it what you wrote in your question.

Which is unpleasant, to say the least. Sorry.

Alun Harford
+1  A: 

Try the following. Not an imperative WPF expert so you may need to alter this slightly

public void Example()
{
    var factory = new FrameworkElementFactory(typeof(TextBlock));
    factory.SetBinding(TextBlock.TextProperty, new Binding("Text"));

    var dataTemplate = new DataTemplate();
    dataTemplate.VisualTree = factory;
    dataTemplate.Seal();
}
JaredPar
+1  A: 

I just checked the online docs - Alun is correct - use the XamlReader. According to Microsoft, the FrameworkElementFactory class does not support all of the features of XAML, and may be deprecated in the future.

Having said that, I've used FrameworkElementFactory to alter DataTemplates on-the-fly, and didn't have any problems.

Mark