简体   繁体   中英

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> 

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM