How can I convert this XAML code into C# code?
<Window.Resources>
<DataTemplate x:Key="itemtemplate">
<TextBlock Text="{Binding Path=Text}"/>
</DataTemplate>
</Window.Resources>
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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With