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();
}
Seal in that time :(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.