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

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

<Window.Resources>
    <DataTemplate x:Key="itemtemplate">
        <TextBlock Text="{Binding Path=Text}"/>
    </DataTemplate>
</Window.Resources> 
+3
source share
3 answers

Try the following. Not a strong WPF expert, so you may need to change this a bit

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

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

Which is unpleasant, to say the least. Unfortunately.

+3
source

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

Having said that, I used FrameworkElementFactory to change DataTemplates on the fly and had no problems.

+2
source

Source: https://habr.com/ru/post/1704309/


All Articles