using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Data; using System.Windows.Markup; using System.Xml; namespace Tango.Core.Components { public static class FrameworkElementSerializer { private class BindingConvertor : ExpressionConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(MarkupExtension)) return true; else return false; } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(MarkupExtension)) { BindingExpression bindingExpression = value as BindingExpression; if (bindingExpression == null) throw new Exception(); return bindingExpression.ParentBinding; } return base.ConvertTo(context, culture, value, destinationType); } public static void Register() { Attribute[] attr = new Attribute[1]; TypeConverterAttribute vConv = new TypeConverterAttribute(typeof(TC)); attr[0] = vConv; TypeDescriptor.AddAttributes(typeof(T), attr); } } static FrameworkElementSerializer() { BindingConvertor.Register(); } /// /// Clones the specified element. /// /// The element. /// public static FrameworkElement Clone(FrameworkElement element) { var sb = new StringBuilder(); var writer = XmlWriter.Create(sb, new XmlWriterSettings { Indent = true, ConformanceLevel = ConformanceLevel.Fragment, OmitXmlDeclaration = true, NamespaceHandling = NamespaceHandling.OmitDuplicates, }); var mgr = new XamlDesignerSerializationManager(writer); // HERE BE MAGIC!!! mgr.XamlWriterMode = XamlWriterMode.Expression; // THERE WERE MAGIC!!! XamlWriter.Save(element, mgr); String xaml = sb.ToString(); StringReader stringReader = new StringReader(xaml); XmlReader xmlReader = XmlReader.Create(stringReader); FrameworkElement cloned = (FrameworkElement)XamlReader.Load(xmlReader) as FrameworkElement; return cloned; } /// /// Serializes the specified element. /// /// The element. /// public static String Serialize(FrameworkElement element) { var sb = new StringBuilder(); var writer = XmlWriter.Create(sb, new XmlWriterSettings { Indent = true, ConformanceLevel = ConformanceLevel.Fragment, OmitXmlDeclaration = true, NamespaceHandling = NamespaceHandling.OmitDuplicates, }); var mgr = new XamlDesignerSerializationManager(writer); // HERE BE MAGIC!!! mgr.XamlWriterMode = XamlWriterMode.Expression; // THERE WERE MAGIC!!! XamlWriter.Save(element, mgr); String xaml = sb.ToString(); return xaml; } /// /// Deserializes the specified xaml. /// /// The xaml. /// public static FrameworkElement Deserialize(String xaml) { StringReader stringReader = new StringReader(xaml); XmlReader xmlReader = XmlReader.Create(stringReader); FrameworkElement cloned = (FrameworkElement)XamlReader.Load(xmlReader) as FrameworkElement; return cloned; } } }