這是一篇很基礎的,大佬就不要看了,也不要噴,謝謝🌺🐔😂😂😂。
在看實例之前,我們先看一下頁面導航Navigate的定義
public bool Navigate(Type sourcePageType); public bool Navigate(Type sourcePageType, object parameter); public bool Navigate(Type sourcePageType, object parameter, NavigationTransitionInfo infoOverride);
有三種方法,其中兩種是可以傳遞參數的
傳遞分兩種,一種帶參數的,一種利用全局變量。
1.帶parameter類型的傳遞
看一個小李子:
xaml代碼定義很簡單,
<TextBlock Text="Name: "/> <TextBox Grid.Column="1" x:Name="txtName" PlaceholderText="Enter name here"/> <TextBlock Grid.Row="1" Text="Age: "/> <TextBox Grid.Row="1" Grid.Column="1" x:Name="txtAge" PlaceholderText="Enter age here"/> <TextBlock Grid.Row="2" Text="Weight: "/> <TextBox Grid.Row="2" Grid.Column="1" x:Name="txtWeight" PlaceholderText="Enter weight here"/> <Button Grid.Row="3" Content="Pass Name" Click="PassName"/> <Button Grid.Row="3" Grid.Column="1" Content="Pass Object" Click="PassObject"/>
主要看一下后台的實現,以及參數是如何傳遞的:
private void PassName(object sender, RoutedEventArgs e) { if (txtName.Text.Trim() == "") return; Frame.Navigate(typeof(ResultPage), txtName.Text.Trim()); } private void PassObject(object sender, RoutedEventArgs e) { if (txtName.Text.Trim() == "" || txtAge.Text.Trim() == "" || txtWeight.Text.Trim() == "") return; User user = new User { Name = txtName.Text.Trim(), Age = Convert.ToInt32(txtAge.Text.Trim()), Weight = Convert.ToDouble(txtWeight.Text.Trim()) }; Frame.Navigate(typeof(ResultPage), user); }
然后新增一個User.cs文件類
public class User { public string Name { get; set; } public int Age { get; set; } public double Weight { get; set; } }
然后在結果頁面ResultPage:
<TextBox x:Name="txtResult"/> <Button Content="Back to MainPage" Click="Back"/>
后台需要重寫OnNavigatedTo,因為我們需要一進入結果頁面,就對傳遞進來的參數進行處理
protected override void OnNavigatedTo(NavigationEventArgs e) { if (e.Parameter.GetType().Equals(typeof(User))) { User user = (User)e.Parameter; txtResult.Text = $"Name: {user.Name} Age: {user.Age} Weight: {user.Weight}"; } else if (e.Parameter.GetType().Equals(typeof(string))) { txtResult.Text = $"Name: {e.Parameter.ToString()}"; } }
點擊主頁面的傳遞按鈕,在結果頁面就可以看到:
User對象被傳遞了過來
2. 利用全局變量傳遞
此方法不要parameter了,只需要在App.xaml.cs里面定義全局變量即可
public string g_string; public User g_user = new User();
使用的時候么,前面加上(Application.Current as App).即可。
還是前面的例子,傳遞User
MainPage后台只需要寫
private void PassObject(object sender, RoutedEventArgs e) { if (txtName.Text.Trim() == "" || txtAge.Text.Trim() == "" || txtWeight.Text.Trim() == "") return; User user = new User { Name = txtName.Text.Trim(), Age = Convert.ToInt32(txtAge.Text.Trim()), Weight = Convert.ToDouble(txtWeight.Text.Trim()) }; (Application.Current as App).g_user = user;//划重點 Frame.Navigate(typeof(ResultPage));
注意Navigate 不加參數了哦
在ResultPage里面寫:
protected override void OnNavigatedTo(NavigationEventArgs e) { User user = (Application.Current as App).g_user; txtResult.Text = $"Name: {user.Name} Age: {user.Age} Weight: {user.Weight}"; }
即可。