如何为现有C# WPF应用快速添加启动页面?
解决WPF启动页与主页面切换的问题
你的错误原因很明确:
- WPF的Window只能有一个根内容元素,直接在Window下放置两个Page,相当于给Window的Content属性赋值了两次,所以触发“内容被多次设置”的报错。
- Page控件是为导航场景设计的,不能直接作为Window的子元素,需要放在Frame、NavigationWindow这类专门的导航容器中。
下面给出两种可行的实现方案,都能实现启动页/主页面全屏显示、无重叠的效果:
方案一:使用Frame实现页面导航
这种方案适合需要保留导航历史的场景,步骤如下:
拆分独立Page文件
分别创建两个独立的Page类文件:StartPage.xaml:编写启动页的UI内容TestPage.xaml:把你原来的DockPanel内容移到这里:<Page x:Class="test.TestPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <DockPanel> <Menu DockPanel.Dock="Top"> </Menu> <TabControl Name="MainTabControl" > </TabControl> </DockPanel> </Page>
修改主Window的XAML
将Window的根元素替换为Frame,默认加载启动页,并隐藏导航栏:<Window x:Class="test.Testing" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:test" mc:Ignorable="d" Closing="Window_Closing" Height="450" Width="800"> <Frame x:Name="MainFrame" NavigationUIVisibility="Hidden" Source="/StartPage.xaml"/> </Window>页面切换逻辑
在启动页的交互事件(比如按钮点击)中,调用Frame的Navigate方法切换到主页面:// 假设StartPage里有个跳转按钮的点击事件 private void GoToMainPage_Click(object sender, RoutedEventArgs e) { var mainWindow = Application.Current.MainWindow as Testing; mainWindow.MainFrame.Navigate(new TestPage()); }
方案二:使用ContentControl切换视图(无导航历史)
如果不需要导航历史,只是单纯切换全屏视图,用UserControl+ContentControl更轻量:
创建UserControl视图
分别创建两个UserControl类文件:StartView.xaml:启动页UI内容MainView.xaml:原DockPanel内容(和方案一的TestPage内容一致,只是把Page换成UserControl)
修改主Window的XAML
用ContentControl作为根元素,默认显示启动页:<Window x:Class="test.Testing" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:test" mc:Ignorable="d" Closing="Window_Closing" Height="450" Width="800"> <ContentControl x:Name="MainContent"> <local:StartView/> </ContentControl> </Window>切换视图逻辑
在启动页的交互事件中,直接替换ContentControl的Content属性:private void EnterMainView_Click(object sender, RoutedEventArgs e) { var mainWindow = Application.Current.MainWindow as Testing; mainWindow.MainContent.Content = new MainView(); }
内容的提问来源于stack exchange,提问作者rickster26ter1
相关产品推荐
相关产品推荐

