how to save canvas c# wpf

Zaug 306 Reputation points
2022-01-22T15:29:25.02+00:00

i work a project in visual studio 2022 and i need to save canvas and parents as a file (not as an image) please help me because it's very important for me...

XAML
XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
769 questions
{count} votes

Accepted answer
  1. Hui Liu-MSFT 41,146 Reputation points Microsoft Vendor
    2022-01-25T06:42:59.427+00:00

    You could try to refer to the XamlWriter/XamReader classes which can help you implement save and load back functionality.(It saves Canvas as .xaml file)
    MainWindow.xaml:

    <StackPanel Orientation="Horizontal" Name="sp">  
            <Canvas x:Name="c" Width="230" Height="200" Background="AliceBlue">  
                <MediaElement x:Name="gif" Source="Ra.gif" LoadedBehavior="Play" Visibility="Visible"/>  
            </Canvas>  
            <Button x:Name="save" Content="save" Width="100" Height="40" Click="save_Click"/>  
            <Button x:Name="load" Content="save" Width="100" Height="40" Click="load_Click"/>  
        </StackPanel>  
    

    Code behind:

     private void save_Click(object sender, RoutedEventArgs e)  
        {  
          FileStream fs = File.Open(@"C:\Desktop\fileName.xaml", FileMode.Create);  
          XamlWriter.Save(c, fs);  
          fs.Close();  
        }  
    
        private void load_Click(object sender, RoutedEventArgs e)  
        {  
          FileStream fs = File.Open(@"C:\Desktop\fileName.xaml", FileMode.Open, FileAccess.Read);  
          Canvas savedCanvas = XamlReader.Load(fs) as Canvas;  
          fs.Close();  
    
          sp.Children.Add(savedCanvas);  
    
        }  
    

    The result:
    168039-1.gif


    If the response is helpful, please click "Accept Answer" and upvote it.
     Note: Please follow the steps in our [documentation][5] to enable e-mail notifications if you want to receive the related email notification for this thread. 

    [5]: https://learn.microsoft.com/en-us/answers/articles/67444/email-notifications.html


0 additional answers

Sort by: Most helpful