Embedd_0913
Embedd_0913

Reputation: 16545

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

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

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

Upvotes: 3

Views: 1965

Answers (3)

Mark
Mark

Reputation: 9428

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.

Upvotes: 3

JaredPar
JaredPar

Reputation: 754515

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();
}

Upvotes: 4

Alun Harford
Alun Harford

Reputation: 3124

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.

Upvotes: 4

Related Questions