UWP 页面间传递参数(常见类型string、int以及自定义类型)
这是一篇很基础的,大佬就不要看了,也不要喷,谢谢🌺🐔😂😂😂。
在看实例之前,我们先看一下页面导航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}"; }
即可。