0

I am getting a System.Windows.Controls.UIElementCollection from a System.Windows.Controls.Canvas object in WPF, it contains a lot of System.Windows.Shape objects

What I am trying to achieve is to serialize these objects in the Canvas, then deserialize them later: like a save/load.

Serialization code:

var items = view.myCanvas.Children;

var mystrXaml = XamlWriter.Save(items);
var fs = File.Create(@"C:\data.xaml");
var sw = new StreamWriter(fs);
sw.Write(mystrXaml);
sw.Close();
fs.Close();

Deserialization code:

var sr = new StreamReader(@"C:\data.xaml");
var xmlReader = new XmlTextReader(sr);
var xamlReader = XamlReader.Load(xmlReader);

Serializing seems to be fine, while deserializing gives this error:

No matching constructor found on type 'System.Windows.Controls.UIElementCollection'. You can use the Arguments or FactoryMethod directives to construct this type.' Line number '1' and line position '22'.

I conceptually understand that there are no parameterless constructors for UIElementCollection as it takes two parameters:

UIElementCollection(UIElement visualParent, FrameworkElement logicalParent);

How can I inject these parameters while the UIElementCollection is getting deserialized? Or am I going about this the wrong way?

Thanks

Small edit: the reason why I thought this was possible is because this library: http://www.codeproject.com/Articles/620154/UniversalSerializer seems to be able to cater exactly for this case, but I can't figure out exactly how it does it, there seems to be some reflection magic.

H.B.
  • 166,899
  • 29
  • 327
  • 400
sinaptik
  • 331
  • 5
  • 15
  • 6
    People should stop serializing the *UI*... – H.B. Sep 09 '13 at 00:03
  • It's only very simple System.Windows.Shape objects. Do you have another suggestion that doesn't involve some Shape saver in a custom format? – sinaptik Sep 09 '13 at 00:05
  • 3
    Usually one should already have a data model backing the UI and serialize that instead. – H.B. Sep 09 '13 at 00:06
  • WPF support MVVM, so create a Model for your shapes, use the Model to display the shapes, and then you can serialize/deserialize your model. – sa_ddam213 Sep 09 '13 at 00:07
  • I save data to a `database` as I am creating the `UI` - properties and what not, then if I need to recreate it I build the `UI` based on the objects in the `DB`. – OneFineDay Sep 09 '13 at 01:51
  • Learn MVVM before you ever write a single line of code in WPF. You don't serialize the UI simply because [UI is Not Data](http://stackoverflow.com/a/14382137/643085) – Federico Berasategui Sep 09 '13 at 02:25
  • @HighCore Bit late for that! Though this is the first time I've mixed serialization with MVVM itself. Now I know! – sinaptik Sep 09 '13 at 03:02

0 Answers0