Usage (Serialize):
Code Snippet
- dlg.FileName = "UIElement File"; // Default file name
- dlg.DefaultExt = ".xaml"; // Default file extension
- dlg.Filter = "Xaml File (.xaml)|*.xaml"; // Filter files by extension
- // Show save file dialog box
- Nullable<bool> result = dlg.ShowDialog();
- // Process save file dialog box results
- if (result == true)
- {
- // Save document
- string filename = dlg.FileName;
- SerializeToXAML(MYUIELEMENTOBJECT, filename);
- }
End of Code Snippet
Usage (Deserialize) - Example using a Canvas:
Code Snippet
- dlg.DefaultExt = ".xaml"; // Default file extension
- dlg.Filter = "Xaml File (.xaml)|*.xaml"; // Filter files by extension
- // Show open file dialog box
- Nullable<bool> result = dlg.ShowDialog();
- // Process open file dialog box results
- if (result == true)
- {
- string filename = dlg.FileName;
- Canvas canvas = DeSerializeXAML(filename) as Canvas;
- // Add all child elements (lines, rectangles etc) to canvas
- while (canvas.Children.Count > 0)
- {
- UIElement obj = canvas.Children[0]; // Get next child
- canvas.Children.Remove(obj); // Have to disconnect it from result before we can add it
- MYCANVASOBJECT.Children.Add(obj); // Add to canvas
- }
- }
End of Code Snippet
Code Snippet
- // De-Serialize XML to UIElement using a given filename.
- public static UIElement DeSerializeXAML(string filename)
- {
- // Load XAML from file. Use 'using' so objects are disposed of properly.
- using (System.IO.FileStream fs = System.IO.File.Open(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read))
- {
- return System.Windows.Markup.XamlReader.Load(fs) as UIElement;
- }
- }
- // Serializes any UIElement object to XAML using a given filename.
- public static void SerializeToXAML(UIElement element, string filename)
- {
- // Use XamlWriter object to serialize element
- string strXAML = System.Windows.Markup.XamlWriter.Save(element);
- // Write XAML to file. Use 'using' so objects are disposed of properly.
- using (System.IO.FileStream fs = System.IO.File.Create(filename))
- {
- {
- streamwriter.Write(strXAML);
- }
- }
- }
End of Code Snippet
No comments:
Post a Comment