StackOverflowException when using XamlWriter.Save() when trying to Clone a User Control
-
03-07-2021 - |
Question
I am using the below method to attempt to clone a TreeViewItem, but once it hits the XamlWriter.Save()
it gives me a StackOverflowException.
The code that triggered this is :
var b = Clone<TreeViewItem>(ViewTree.ItemContainerGenerator.ContainerFromIndex(0) as TreeViewItem);
Where ViewTree is the name of my TreeView.
public static T Clone<T>(T from) {
string objStr = System.Windows.Markup.XamlWriter.Save(from);
System.IO.StringReader stringReader = new System.IO.StringReader(objStr);
System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(stringReader);
object clone = System.Windows.Markup.XamlReader.Load(xmlReader);
return (T)clone;
}
Solution
Check if this TreeView has some cycle in it. For example: Some treeview node (or children of it children) has a child that point to the parent node. The StackOverflowException is generally for recursions out of memory.
OTHER TIPS
This works for me:
System.Xaml.XamlServices.Save(obj);
from System.Xaml.dll
It handles circular references properly.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow