C# 在页面之间导航而不会丢失数据 [英] C# Navigating Between Pages Without losing Data

查看:24
本文介绍了C# 在页面之间导航而不会丢失数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一项任务是将数据传递到我理解的另一个页面.但是,当我返回页面时,如何让数据保留下来?有人可以解释一下这是如何工作的.

One of my assignments is to pass data to another page which I understand. But how do I get the data to stay when I go back to the Page? Can someone explain how this works.

 public sealed partial class MainPage : Page
    {
       string userName;
       public MainPage()
     {

        this.InitializeComponent();
    }

    private void btnPage2_Click(object sender, RoutedEventArgs e)
    {
        Frame.Navigate(typeof(Page2) ,  userName);
    }

    private void btnName_Click(object sender, RoutedEventArgs e)
    {
        userName = Convert.ToString(txtname.Text);
    }
}

推荐答案

我已经回答了一个类似的问题.那里的答案也适用于这个问题,但是在您的情况下,您特别关注有问题的数据部分,因此在这里您应该特别注意答案的第二部分 - 使用 ViewModel这将比页面本身更有效将是最有益的解决方案.但是,使用 NavigationCacheMode 也足够了,因为页面类本身及其字段将被保留.

I have answered a similar question here. The answer there applies to this problem as well, however in your case you are especially focusing on the data part in question, so here you should pay special attention to the second part of the answer - using a ViewModel that will outlive the page itself would be the most beneficial solution. However using NavigationCacheMode will be sufficient as well, as the page class itself along with its fields will be preserved.

此处提供了第三个选项,即使用 static 作为您要保留的字段,或者创建一个 static 或将保存数据的单例类.然而,与 ViewModel 解决方案相比,这有一个缺点,因为它不允许在导航堆栈中多次使用具有不同状态数据的单个页面.

There is a third option available here, which is using static for the field you want to keep, or creating a static or singleton class that will hold the data. This however comes with a disadvantage when compared to the ViewModel solution as it does not easily allow having a single page multiple times in the navigation stack with different state data.

这篇关于C# 在页面之间导航而不会丢失数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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