[Windows Store App 開發筆記] 「頁面巡覽」以及「多參數傳遞」

[Windows Store App 開發筆記] 「頁面巡覽」以及「多參數傳遞」

前言


 

最近在試著開發Windows Store App,所以對頁面切換以及參數傳遞做了一些研究,今天就來和大家分享,如何利用類別定義,做到頁面間多參數的傳遞。

 

以下是一個簡單的範例,我們將兩個integer的變數,一起傳到第二頁做加總的動作。

 

實作


 

1. MainPage.xaml

   1: <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
   2:     <Grid.RowDefinitions>
   3:         <RowDefinition Height="35*"/>
   4:         <RowDefinition Height="157*"/>
   5:     </Grid.RowDefinitions>
   6:     <StackPanel Grid.Row="0" Orientation="Horizontal">
   7:         <TextBlock x:Name="show" Text="10+10=" FontSize="36" VerticalAlignment="Center"/>
   8:         <Button x:Name="NextBtn" Content="Show Ans" FontSize="36" Click="NextBtn_Click"/>
   9:     </StackPanel>
  10: </Grid>

 

2. MainPage.xaml.cs

在這之中我們定義了一個類別Num,用來存兩個integer的變數

   1: class Num
   2: {
   3:     public int num1 { get; set; }
   4:     public int num2 { get; set; }
   5:     public Num(int _num1, int _num2)
   6:     {
   7:         num1 = _num1;
   8:         num2 = _num2;
   9:     }
  10: }
  11: public sealed partial class MainPage : Page
  12: {
  13:     public MainPage()
  14:     {
  15:         this.InitializeComponent();
  16:     }
  17:     private void NextBtn_Click(object sender, RoutedEventArgs e)
  18:     {
  19:         Num num = new Num(10, 10);
  20:         this.Frame.Navigate(typeof(MainPage2), num);
  21:     }
  22:  
  23: }

 

3. MainPage2.xaml

   1: <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
   2:     <Grid.RowDefinitions>
   3:         <RowDefinition Height="35*"/>
   4:         <RowDefinition Height="157*"/>
   5:     </Grid.RowDefinitions>
   6:     <StackPanel Grid.Row="0" Orientation="Horizontal">
   7:         <TextBlock x:Name="show" Text="" FontSize="36" VerticalAlignment="Center"/>
   8:         <Button x:Name="BackBtn" Content="Back" FontSize="36" Click="BackBtn_Click"/>
   9:     </StackPanel>
  10: </Grid>

 

4. MainPage2.xaml.cs

註:GoBack()是一個相當好用的API喔!!!

   1: public sealed partial class MainPage2 : Page
   2: {
   3:     public MainPage2()
   4:     {
   5:         this.InitializeComponent();
   6:     }
   7:     protected override void OnNavigatedTo(NavigationEventArgs e)
   8:     {
   9:         Num tmp = (Num)e.Parameter;
  10:         int ans = tmp.num1 + tmp.num2;
  11:         show.Text = ans.ToString();
  12:     }
  13:  
  14:     private void BackBtn_Click(object sender, RoutedEventArgs e)
  15:     {
  16:         this.Frame.GoBack();
  17:     }
  18: }

 

執行結果:

9

10

 

所以之後需要一次傳遞多個參數,自己定義一個類別來傳遞就可以囉,相當輕鬆簡單。