Question

I have a FrameworkElement, such as StackPanel with children, I need to create a DataTempltate whose VisualTree property is my FrameworkElement. To do this work I need to convert my FrameworkElement in the equivalent FrameworkElementFactory.

How can I do?

Was it helpful?

Solution

You can probably use the XamlWriter and XamlReader classes to get a copy of the XAML used in your control, and use it to build another control

string panelXaml = XamlWriter.Save(myStackPanel);

StringReader stringReader = new StringReader(panelXaml);
XmlReader xmlReader = XmlReader.Create(stringReader);
StackPanel newStackPanel = (StackPanel)XamlReader.Load(xmlReader);

I think this will only copy the StackPanel, so you'll probably have to copy it's children the same way too.

Also per the Remarks section on MSDN for the FrameworkElementFactory

This class is a deprecated way to programmatically create templates, which are subclasses of FrameworkTemplate such as ControlTemplate or DataTemplate; not all of the template functionality is available when you create a template using this class. The recommended way to programmatically create a template is to load XAML from a string or a memory stream using the Load method of the XamlReader class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top