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> 

3 Answers 3

4

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();
}
Sign up to request clarification or add additional context in comments.

3 Comments

Why are you calling Seal()? This fixed an issue I had with creating a template and binding it to a Telerik Grid but in all the examples I found for creating a DateTemplate dynamically, other people weren't used Seal()?
@RalphWillgoss it's been 4 years since I wrote this answer and I've forgotten my reason for calling Seal in that time :(
Thanks, I might do some more research and see what I can find. It could be to do with the Telerik control. I have it all working, want to know whats going on under the hood :-)
4

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.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.