Saving the State of a WPF Application Page

浪尽此生 提交于 2019-12-20 04:22:35

问题


I am creating a software in WPF, and, in the software, the User can load an image, and configure a map.

Basically, once the Image (of a map) is loaded the user can add other images (like a picture of a treasure or a monster, etc) drag and drop them within the image of the Map.

When the user closes the software, and reopens it, I want the last image opened, and the UI elements added to be in the same place, like how the User had set up, before closing the application.

One way I can think of, is storing the image file in a byte array, or saving the file location , and the other UI element positions in a text file and checking it every time the application is loaded.

However, is there an easier way to solve this? Is there a way I can store the state of the WPF application Page?


回答1:


Perhaps you could save the Windows xaml on exit and reload on application start.

    public MainWindow()
    {
        InitializeComponent();
        Loaded += new RoutedEventHandler(MainWindow_Loaded);
        Closing += new CancelEventHandler(MainWindow_Closing);
    }


    void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
       LoadExternalXaml();
    }

    void MainWindow_Closing(object sender, CancelEventArgs e)
    {
        SaveExternalXaml();
    }


    public void LoadExternalXaml()
    {
        if (File.Exists(@"C:\Test.xaml"))
        {
            using (FileStream stream = new FileStream(@"C:\Test.xaml", FileMode.Open))
            {
                this.Content = XamlReader.Load(stream);
            }
        }
    }

    public void SaveExternalXaml()
    {
        using (FileStream stream = new FileStream(@"C:\Test.xaml", FileMode.Create))
        {
            XamlWriter.Save(this.Content, stream);
        }
    }


来源:https://stackoverflow.com/questions/13674345/saving-the-state-of-a-wpf-application-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!