You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UWP页面切换后TextBox内容重置问题求助

解决UWP返回页面时TextBox内容重置的问题

问题原因

默认情况下,UWP的Frame导航栈中,页面被导航离开后,系统可能会销毁页面实例以释放资源。调用GoBack返回时,会重新创建MainPage的新实例,导致TextBox的内容丢失。


解决方案

方法一:启用页面缓存

通过配置Frame的缓存机制,让系统保留页面实例,返回时直接复用原有实例,避免内容重置。

  1. 在App.xaml.cs的OnLaunched方法中设置Frame的缓存大小:
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
    Frame rootFrame = Window.Current.Content as Frame;

    if (rootFrame == null)
    {
        rootFrame = new Frame();
        // 设置缓存数量,按需调整,这里保留2个页面实例
        rootFrame.CacheSize = 2;
        Window.Current.Content = rootFrame;
    }

    if (e.PrelaunchActivated == false)
    {
        if (rootFrame.Content == null)
        {
            rootFrame.Navigate(typeof(MainPage), e.Arguments);
        }
        Window.Current.Activate();
    }
}
  1. 让MainPage允许被缓存,二选一即可:
  • 在MainPage的构造函数中设置:
public MainPage()
{
    this.InitializeComponent();
    this.NavigationCacheMode = NavigationCacheMode.Required;
}
  • 或者在MainPage的XAML中直接配置:
<Page x:Class="YourAppName.MainPage"
      ...
      NavigationCacheMode="Required">

方法二:手动保存并恢复内容

如果不想启用页面缓存,可以在页面导航前后手动保存和恢复TextBox的内容。

方式1:使用页面字段临时保存

private string _savedText;

protected override void OnNavigatedFrom(NavigationEventArgs e)
{
    base.OnNavigatedFrom(e);
    // 导航离开时保存内容
    _savedText = MyTextBox.Text;
}

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    // 返回时恢复内容
    if (!string.IsNullOrEmpty(_savedText))
    {
        MyTextBox.Text = _savedText;
    }
}

方式2:使用本地设置持久化保存(支持应用重启后恢复)

protected override void OnNavigatedFrom(NavigationEventArgs e)
{
    base.OnNavigatedFrom(e);
    var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
    localSettings.Values["TextBoxContent"] = MyTextBox.Text;
}

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
    if (localSettings.Values.ContainsKey("TextBoxContent"))
    {
        MyTextBox.Text = localSettings.Values["TextBoxContent"].ToString();
    }
}

内容的提问来源于stack exchange,提问作者MinecraftWolf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 19:42:30