Search code examples
c#sqlxamluielement

How to save UIElements in a Database and restore them later?


Imagine that I created an app which lets you paint paths within a grid.

So when every time you paint something, a new path element is added as children to my Grid UI Element.

So this is my Grid before something has been painted:

    <Grid x:Name="myGrid" Grid.Row="0" PointerMoved="myGrid_PointerMoved" PointerPressed="myGrid_PointerPressed" PointerReleased="myGrid_PointerReleased" ></Grid>

And when you paint something the following is added programmtically as a children of the grid above:

<Path Stroke="Black" StrokeThickness="1">
  <Path.Data>
    <PathGeometry>
      <PathFigure StartPoint="10,50">
        <LineSegment Point="200,70" />
      </PathFigure>
    </PathGeometry>
  </Path.Data>
</Path>

So each new paint action will add one path like this one as a children of my grid.

Now I would like to save early made Paths in my SQL Database to restore them later but I don't know how I could save an xml XAML UI element in my SQL Database and restore it later.

Is it possible to do this by binding or to save my XAML Objects as a string and parse them later? Whats the best practice here?


Solution

  • Try to serialize your XAML-Control and save it as a string to the database. Later you can load it like this:

    UIElement cXamlElements = (UIElement)XamlReader.Parse("MY XAML CODE");
    

    Like this: XAML Serialization