StackOverflowException when using XamlWriter.Save() when trying to Clone a User Control

StackOverflow https://stackoverflow.com/questions/12518210

  •  03-07-2021
  •  | 
  •  

문제

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;
 }
도움이 되었습니까?

해결책

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.

다른 팁

This works for me:

 System.Xaml.XamlServices.Save(obj);

from System.Xaml.dll

It handles circular references properly.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top