WPF C#页面导航时TextBlock输入内容无法保留问题求助
WPF Frame导航返回页面数据丢失问题解决(.NET 6)
核心原因
你猜的没错——每次点击导航按钮都重新创建页面实例,之前输入的内容自然会被清空。KeepAlive=true只在页面实例被Frame缓存时生效,如果每次都new新对象,这个属性根本起不到作用。
解决方案
1. 缓存页面实例(最直接的解决方式)
在主窗口中维护一个页面实例的缓存字典,确保每个页面只创建一次,重复复用:
// MainWindow.xaml.cs private readonly Dictionary<Type, Page> _pageCache = new(); // 通用导航方法 private void NavigateToPage<T>() where T : Page, new() { if (!_pageCache.TryGetValue(typeof(T), out var targetPage)) { targetPage = new T(); _pageCache.Add(typeof(T), targetPage); } MainFrame.Navigate(targetPage); } // 侧边栏按钮点击示例 private void Page1Btn_Click(object sender, RoutedEventArgs e) { NavigateToPage<Page1>(); }
之后所有侧边栏导航都调用这个通用方法,不再手动new Page(),返回时就会回到之前的实例,输入内容完全保留。
2. 配置Frame的导航缓存模式
如果不想自己维护缓存字典,可以直接设置Frame的NavigationCacheMode,让Frame自动缓存页面实例:
<!-- MainWindow.xaml 中配置Frame --> <Frame x:Name="MainFrame" NavigationCacheMode="Required"/>
Required:强制缓存该Frame导航过的所有页面(只要页面的KeepAlive不为false)Enabled:仅缓存标记了KeepAlive=true的页面
注意:如果页面手动设置了KeepAlive=false,即使Frame设了缓存模式也不会生效,确保页面的KeepAlive保持默认的true即可。
3. 运行时数据容器(适合跨页面共享数据场景)
如果不需要缓存整个页面,只是想保留输入数据,可以创建一个静态类作为运行时数据容器,页面绑定到容器的属性:
// 静态数据容器类 public static class RuntimeDataHolder { public static string Page1TextContent { get; set; } = string.Empty; public static string Page2TextContent { get; set; } = string.Empty; } // Page1.xaml 绑定示例 <TextBlock Text="{Binding Source={x:Static local:RuntimeDataHolder.Page1TextContent}, Mode=TwoWay}"/>
切换页面时数据会存在静态类中,返回页面时绑定会自动拉取最新值,内容不会丢失。
内容的提问来源于stack exchange,提问作者calico
相关产品推荐
相关产品推荐

