I'm currently working on an editor like WPF application where you can choose to edit a control and then a dialog opens with a copy of the control in it. For the copying of the control I use the XamlReader.Parse(string)
and XamlWriter.Save(obj)
.
Now there are some (custom) controls than contain an Image control who has their Source
set to an WriteableBitmap
. The Bitmap is not serializable so the serializer is throwing some exceptions, but that's not the main problem because it isn't required to be serialized because it gets changed later anyways.
Is there a way to Serialize a WPF-Control and tell the Serializer to ignore a property of its children or override it with something that is serializeable (like null) in runtime?
I've already tried to manually set the source Property before and after serialization but for some unkown reason I can't change the Source of the deserialized control.
Code for the dialog
public void LaunchEditor()
{
Editor dlg = new Editor ();
dlg.Owner = Application.Current.MainWindow;
dlg.SetTemplateString(XamlWriter.Save(this));
if (dlg.ShowDialog() ?? false)
{
string s = dlg.GetTemplateString();
CustomControlType c = (CustomControlType)XamlReader.Parse(s);
Content = c;
}
}
Code for serialization
public void SetTemplateString(string template)
{
Placeholder = (CustomControlType)XamlReader.Parse(template);
/*Formatting Stuff*/
}
public string GetTemplateString()
{
StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings()
{
Indent = true
};
XmlWriter writer = XmlWriter.Create(sb,settings);
XamlDesignerSerializationManager mgr = new XamlDesignerSerializationManager(writer);
XamlWriter.Save(Placeholder, mgr);
return sb.ToString();
}
Custom control that contains the Image
public partial class RollingViewControl : ContentConstrol
{
private RollingBitmap _bmp;
public RollingViewControl()
{
_bmp = new RollingBitmap(256, 256);
InitializeComponent();
ImageDisplay.Source = _bmp.Bitmap;
}
}
RollingBitmap
is a Class for Manupilating the WriteableBitmap
who is a Property of this Class.
The problem is the Source property of the Image Control, when serializing the Control the Source also gets serialized. Because it is precompiled code I cannot set any Attributes and I haven't found any way to apply XmlAttributeOverrides
to the XamlWriter
.