Click here to Skip to main content
15,868,141 members
Articles / Desktop Programming / WPF
Tip/Trick

XAML Serialization

Rate me:
Please Sign up or sign in to vote.
4.86/5 (4 votes)
23 May 2010CPOL 26.9K   6   1
Serialization of WPF Framework Elements
In my last windows project I was supposed to create a Layout Management tool where user can create web layouts through a windows application.

This tool is having following functionality.

1- Create multiple rows.
2- Create multiple columns.
3- Merge Cell.
4- Split Cells

Requirements were similar to the table control present in the MS Office, where user can resize rows.

I implemented this using WPF Grid control and the resizing part is done through GridSplitter control. While implementing this tool the main issue I faced was to persist the layout, so that it can be loaded exactly same every time (mainly height/width of rows and columns and the exact location of the GridSplitter).

For persisting I thought of standard serialization technique, but it’s not possible to serialize a WPF framework element using binary or Xml serialization technique.

So finally I decided to store the XAML of the grid to the database and use the XAML to load the layout back.
I have used following code to generate the XAML code from the grid.

private XmlDocument GetXAMLFromGrid()
        {
            StringBuilder outstr = new StringBuilder();
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.OmitXmlDeclaration = true;
            XamlDesignerSerializationManager dsm = new XamlDesignerSerializationManager(XmlWriter.Create(outstr, settings));
            dsm.XamlWriterMode = XamlWriterMode.Expression;
            XamlWriter.Save(ivGrid, dsm);
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(outstr.ToString());
            return doc;
        }


For restoring the Grid from the XAML I used following code.

private Grid GetGidFromXAML(string xamlText)
        {
            Grid grid = (Grid)XamlReader.Parse(xamlText);
            return grid;
        }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India
Its me Smile | :)

Comments and Discussions

 
QuestionImage bound to resource Pin
mbyamukama2-Apr-12 23:38
mbyamukama2-Apr-12 23:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.