使用Frame和Page構建導航(嚮導)功能
WPF中Frame導航框架使得軟體嚮導工具的開發變得十分容易,Frame中GoFront和GoBack方法可以直接向前翻導航頁或向後翻導航頁。
XAML代碼
主窗口代碼:
<Grid> <Frame x:Name="fmNavigation" NavigationUIVisibility="Hidden"/> <Button x:Name="btnGoFront" Click="btnGoFront_Click" Width="160" Height="40" Content="上一頁" FontSize="20" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="200,0,0,50"/> <Button x:Name="btnGoBack" Click="btnGoBack_Click" Width="160" Height="40" Content="下一頁" FontSize="20" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="0,0,200,50"/></Grid>
新建3個Page導航頁,添加對應內容:
<!--第1頁內容--><TextBlock Text=="第1頁" Foreground="Red" FontSize="48" HorizontalAlignment="Center" VerticalAlignment="Center"/><!--第2頁內容--><TextBlock Text=="第2頁" Foreground="Red" FontSize="48" HorizontalAlignment="Center" VerticalAlignment="Center"/><!--第3頁內容--><TextBlock Text=="第3頁" Foreground="Red" FontSize="48" HorizontalAlignment="Center" VerticalAlignment="Center"/>
整個項目結構如下圖:
後台代碼
using System;using System.Collections.Generic;using System.Windows;using System.Windows.Controls;using System.Windows.Navigation;namespace Navigation{ /// <summary> /// MainWindow.xaml 的交互邏輯 /// </summary> public partial class MainWindow : Window { List<Page> Pages = new List<Page>(); Int32 AddIndex = 0; public MainWindow() { InitializeComponent(); Pages.Add(new Page3()); Pages.Add(new Page2()); Pages.Add(new Page1()); } private void Window_Loaded(object sender, RoutedEventArgs e) { fmNavigation.Navigate(Pages[0]); fmNavigation.LoadCompleted += AddPage; } private void AddPage(object sender, NavigationEventArgs e) { AddIndex++; if (AddIndex == Pages.Count) { fmNavigation.LoadCompleted -= AddPage; return; } fmNavigation.Navigate(Pages[AddIndex]); } private void btnGoBack_Click(object sender, RoutedEventArgs e) { if (fmNavigation.CanGoBack) { fmNavigation.GoBack(); } } private void btnGoFront_Click(object sender, RoutedEventArgs e) { if (fmNavigation.CanGoForward) { fmNavigation.GoForward(); } } }}
窗口初始化時嚮導航頁容器Pages添加所有導航頁(發序列添加,最後一個就是第一頁),在窗口載入後,載入容器里第一頁並在Frame導航框架的完成頁面載入(LoadCompleted)事件中添載入入其他頁面的委託,當嵌套觸發載入完容器里最後一頁(實際第一頁)時,取消委託的關聯。
點擊翻頁按鈕觸發框架的前後翻頁功能。
最終效果:

參考資料:
關於C# wpf Frame 一次載入多個Page 的問題推薦閱讀:
※[數據結構]表達式樹——手動eval()
※精確的小數-decimal初探
※計算物理導航
※假如你可以個人主導 C++,你打算怎樣裁剪、擴充和訂製 C++ 來達到你心中最完美的 C++?
※定時器setTimeout()的小秘密
TAG:WindowsPresentationFoundationWPF | 編程 |

