Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

wpf

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

<Window.Resources>
    <DataTemplate x:Key="itemtemplate">
        <TextBlock Text="{Binding Path=Text}"/>
    </DataTemplate>
</Window.Resources> 
like image 698
Embedd_0913 Avatar asked Dec 09 '25 12:12

Embedd_0913


2 Answers

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();
}
like image 180
JaredPar Avatar answered Dec 11 '25 03:12

JaredPar


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.

like image 37
Alun Harford Avatar answered Dec 11 '25 02:12

Alun Harford



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!