Saturday, 6 December 2014

Serialize and Deserialize any WPF UIElement to XAML and Back!

The following snippet uses XamlReader and XamlWriter objects to serialize and deserialize WPF UIElements (Like Canvas for example!) to XAML and back.

Usage (Serialize):
Code Snippet
  1. Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
  2. dlg.FileName = "UIElement File"; // Default file name
  3. dlg.DefaultExt = ".xaml"; // Default file extension
  4. dlg.Filter = "Xaml File (.xaml)|*.xaml"; // Filter files by extension
  5.  
  6. // Show save file dialog box
  7. Nullable<bool> result = dlg.ShowDialog();
  8.  
  9. // Process save file dialog box results
  10. if (result == true)
  11. {
  12.     // Save document
  13.     string filename = dlg.FileName;
  14.     SerializeToXAML(MYUIELEMENTOBJECT, filename);
  15. }
End of Code Snippet


Usage (Deserialize) - Example using a Canvas:
Code Snippet
  1. Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
  2. dlg.DefaultExt = ".xaml"; // Default file extension
  3. dlg.Filter = "Xaml File (.xaml)|*.xaml"; // Filter files by extension
  4.  
  5. // Show open file dialog box
  6. Nullable<bool> result = dlg.ShowDialog();
  7.  
  8. // Process open file dialog box results
  9. if (result == true)
  10. {
  11.     string filename = dlg.FileName;
  12.     Canvas canvas = DeSerializeXAML(filename) as Canvas;
  13.  
  14.     // Add all child elements (lines, rectangles etc) to canvas
  15.     while (canvas.Children.Count > 0)
  16.     {
  17.         UIElement obj = canvas.Children[0]; // Get next child
  18.         canvas.Children.Remove(obj); // Have to disconnect it from result before we can add it
  19.         MYCANVASOBJECT.Children.Add(obj); // Add to canvas
  20.     }
  21. }
End of Code Snippet


Code Snippet
  1. // De-Serialize XML to UIElement using a given filename.
  2. public static UIElement DeSerializeXAML(string filename)
  3. {
  4.     // Load XAML from file. Use 'using' so objects are disposed of properly.
  5.     using (System.IO.FileStream fs = System.IO.File.Open(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read))
  6.     {
  7.         return System.Windows.Markup.XamlReader.Load(fs) as UIElement;
  8.     }
  9. }
  10.  
  11. // Serializes any UIElement object to XAML using a given filename.
  12. public static void SerializeToXAML(UIElement element, string filename)
  13. {
  14.     // Use XamlWriter object to serialize element
  15.     string strXAML = System.Windows.Markup.XamlWriter.Save(element);
  16.  
  17.     // Write XAML to file. Use 'using' so objects are disposed of properly.
  18.     using (System.IO.FileStream fs = System.IO.File.Create(filename))
  19.     {
  20.         using (System.IO.StreamWriter streamwriter = new System.IO.StreamWriter(fs))
  21.         {
  22.             streamwriter.Write(strXAML);
  23.         }
  24.     }
  25. }
End of Code Snippet

No comments: