保存 WPF 应用程序页面的状态 [英] Saving the State of a WPF Application Page

查看:41
本文介绍了保存 WPF 应用程序页面的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 WPF 中创建一个软件,并且在该软件中,用户可以加载图像并配置地图.

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.

当用户关闭软件并重新打开它时,我希望打开最后一张图片,并将添加的 UI 元素放在同一个位置,就像用户在关闭应用程序之前的设置一样.

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.

我能想到的一种方法是,将图像文件存储在字节数组中,或者将文件位置和其他 UI 元素位置保存在文本文件中,并在每次加载应用程序时进行检查.

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.

但是,有没有更简单的方法来解决这个问题?有没有办法可以存储 WPF 应用程序页面的状态?

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

推荐答案

也许您可以在退出时保存 Windows xaml,并在应用程序启动时重新加载.

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);
        }
    }

这篇关于保存 WPF 应用程序页面的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆