.NET MAUI中如何将注册页面数据传递至设置页面
.NET MAUI 页面间数据传递问题:注册页到设置页传值失败
我是.NET MAUI新手,尝试将注册页面(Signup Page)用户填写的个人信息传递到设置页面(Setting Page),但没能成功实现。以下是相关代码:
注册页面XAML代码
<Entry x:Name="fullNameEntry" Text="{Binding FullName}" Placeholder="Alice Wong Li Li" PlaceholderColor="{StaticResource BlurTextColor}" TextColor="{StaticResource NormalTextColor}" FontFamily="WorkSansRegular" CharacterSpacing="-0.5" FontSize="16"/> <Entry x:Name="emailEntry" Placeholder="example@gmail.com" Text="{Binding Email}" PlaceholderColor="{StaticResource BlurTextColor}" TextColor="{StaticResource NormalTextColor}" FontFamily="WorkSansRegular" CharacterSpacing="-0.5" FontSize="16"/> <Entry x:Name="PasswordEntry" Text="{Binding Password}" TextColor="{StaticResource NormalTextColor}" FontFamily="WorkSansRegular" CharacterSpacing="-0.5" FontSize="16"/> <Entry x:Name="ConfirmPasswordEntry" Text="{Binding ConfirmPassword, Mode=TwoWay}" TextColor="{StaticResource NormalTextColor}" FontFamily="WorkSansRegular" CharacterSpacing="-0.5" FontSize="16"> </Entry> <editors:SfMaskedEntry x:Name="phoneNumberEntry" Placeholder="0123456789" MaskType="RegEx" Mask="" PlaceholderColor="{StaticResource BlurTextColor}" TextColor="{StaticResource NormalTextColor}" FontFamily="WorkSansRegular" FontSize="16"/> <Entry x:Name="homeAddressEntry" Text="{Binding HomeAddress}" Placeholder="" PlaceholderColor="{StaticResource BlurTextColor}" TextColor="{StaticResource NormalTextColor}" FontFamily="WorkSansRegular" CharacterSpacing="-0.5" FontSize="16"/>
设置页面XAML代码
<listView:SfListView x:Name="PersonalInformationListView" Grid.Row="1" Orientation="Vertical" VerticalOptions="Start" ScrollBarVisibility="Always" BackgroundColor="Azure" ItemSize="{OnPlatform 350}" ItemSpacing="{OnPlatform '0,0,0,0'}" ItemsSource="{Binding PersonalInfo}"> <listView:SfListView.ItemTemplate> <DataTemplate> <Grid> <Grid.RowDefinitions> <RowDefinition Height="{OnPlatform Auto}"/> <RowDefinition Height="{OnPlatform 1}"/> <RowDefinition Height="{OnPlatform Auto}"/> <RowDefinition Height="{OnPlatform 1}"/> <RowDefinition Height="{OnPlatform Auto}"/> <RowDefinition Height="{OnPlatform 1}"/> <RowDefinition Height="{OnPlatform Auto}"/> <RowDefinition Height="{OnPlatform 1}"/> </Grid.RowDefinitions> <Frame Grid.Row="0" Padding="{OnPlatform 0}" CornerRadius="0" BorderColor="Transparent" BackgroundColor="{StaticResource FrameBackgroundColor}" HeightRequest="{OnPlatform 80}"> <Label Text="{Binding FullName}" Grid.Row="1" TextColor="{StaticResource ActiveButtonTextColor}" VerticalOptions="Center" LineBreakMode="WordWrap" FontFamily="WorkSansMedium" FontSize="{OnPlatform 18}" Padding="{OnPlatform 15}"/> </Frame> <BoxView Grid.Row="1" Color="{StaticResource Gray400}" HeightRequest="{OnPlatform 1}"/> <Frame Grid.Row="2" Padding="{OnPlatform 0}" CornerRadius="0" BorderColor="Transparent" BackgroundColor="{StaticResource FrameBackgroundColor}" HeightRequest="{OnPlatform 80}"> <Label Text="{Binding Email}" Grid.Row="1" TextColor="{StaticResource ActiveButtonTextColor}" VerticalOptions="Center" LineBreakMode="WordWrap" FontFamily="WorkSansMedium" FontSize="{OnPlatform 18}" Padding="{OnPlatform 15}"/> </Frame> <BoxView Grid.Row="3" Color="{StaticResource Gray400}" HeightRequest="{OnPlatform 1}"/> <Frame Grid.Row="4" Padding="{OnPlatform 0}" CornerRadius="0" BorderColor="Transparent" BackgroundColor="{StaticResource FrameBackgroundColor}" HeightRequest="{OnPlatform 80}"> <Label Text="{Binding PhoneNumber}" Grid.Row="1" TextColor="{StaticResource ActiveButtonTextColor}" VerticalOptions="Center" LineBreakMode="WordWrap" FontFamily="WorkSansMedium" FontSize="{OnPlatform 18}" Padding="{OnPlatform 15}"/> </Frame> <BoxView Grid.Row="5" Color="{StaticResource Gray400}" HeightRequest="{OnPlatform 1}"/> <Frame Grid.Row="6" Padding="{OnPlatform 0}" CornerRadius="0" BorderColor="Transparent" BackgroundColor="{StaticResource FrameBackgroundColor}" HeightRequest="{OnPlatform 80}"> <Label Text="{Binding HomeAddress}" Grid.Row="1" TextColor="{StaticResource ActiveButtonTextColor}" VerticalOptions="Center" LineBreakMode="WordWrap" FontFamily="WorkSansMedium" FontSize="{OnPlatform 18}" Padding="{OnPlatform 15}"/> </Frame> <BoxView Grid.Row="7" Color="{StaticResource Gray400}" HeightRequest="{OnPlatform 1}"/> </Grid> </DataTemplate> </listView:SfListView.ItemTemplate> </listView:SfListView>
SignupPageViewModel代码
namespace fitnessStudioMobileApp.ViewModels { public partial class SignupPageViewModel : ObservableObject, INotifyPropertyChanged { [ObservableProperty] private string fullName; [ObservableProperty] private string homeAddress; [ObservableProperty] private string phoneNumber; private string userName; private string userPassword; private string email; private string password; public string UserName { get => userName; set { userName = value; RaisePropertyChanged("UserName"); } } public string UserPassword { get => userPassword; set { userPassword = value; RaisePropertyChanged("UserPassword"); } } public string Email { get => email; set { email = value; RaisePropertyChanged("Email"); } } public string Password { get => password; set { password = value; RaisePropertyChanged("Password"); } } private PersonalInfo _personalInfo; public PersonalInfo PersonalInfo { get => _personalInfo; set => SetProperty(ref _personalInfo, value); } private void RaisePropertyChanged(string v) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(v)); } public SignupPageViewModel() { LoadUserProfile(); } public void LoadUserProfile() { var personalInfoJson = Preferences.Get("PersonalInfo", string.Empty); if (!string.IsNullOrEmpty(personalInfoJson)) { Debug.WriteLine("Loading user profile..."); PersonalInfo = JsonConvert.DeserializeObject<PersonalInfo>(personalInfoJson); // Update ViewModel properties with loaded data FullName = PersonalInfo.FullName; Email = PersonalInfo.Email; PhoneNumber = PersonalInfo.PhoneNumber; HomeAddress = PersonalInfo.HomeAddress; } } private async void RegisterUserCommandTappedAsync() { try { var authProvider = new FirebaseAuthProvider(new FirebaseConfig(webApiKey)); var auth = await authProvider.CreateUserWithEmailAndPasswordAsync(Email, Password); string token = auth.FirebaseToken; var personalInfo = new PersonalInfo { FullName = this.FullName, Email = this.Email, PhoneNumber = this.PhoneNumber, HomeAddress = this.HomeAddress }; if (token != null) { var personalInfoJson = JsonConvert.SerializeObject(personalInfo); Preferences.Set("PersonalInfo", personalInfoJson); await App.Current.MainPage.DisplayAlert("Congratulation!", "User Registered successfully", "OK"); await Shell.Current.GoToAsync("LoginPage"); } } catch (Exception ex) { await App.Current.MainPage.DisplayAlert("Alert", ex.Message, "OK"); } } } }
PersonalInfo.cs代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Maui.Controls; using System.ComponentModel; namespace fitnessStudioMobileApp.Model { public class PersonalInfo : INotifyPropertyChanged { #region Fields private string? fullName; private string? email; private string? phoneNumber; private string? homeAddress; #endregion #region Constructor public PersonalInfo() { } #endregion #region Properties public string? FullName { get { return fullName; } set { fullName = value; OnPropertyChanged("FullName"); } } public string? Email { get { return email; } set { email = value; OnPropertyChanged("Email"); } } public string? PhoneNumber { get { return phoneNumber; } set { phoneNumber = value; OnPropertyChanged("PhoneNumber"); } } public string? HomeAddress { get { return homeAddress; } set { homeAddress = value; OnPropertyChanged("HomeAddress"); } } #endregion #region Interface Member public event PropertyChangedEventHandler? PropertyChanged; public void OnPropertyChanged(string name) { if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion } }
解决方案
1. 补充设置页面ViewModel实现
创建SettingPageViewModel,读取Preferences中存储的用户信息:
using fitnessStudioMobileApp.Model; using Newtonsoft.Json; using System.ComponentModel; using Microsoft.Maui.Storage; using System.Diagnostics; namespace fitnessStudioMobileApp.ViewModels { public class SettingPageViewModel : INotifyPropertyChanged { private PersonalInfo _personalInfo; public PersonalInfo PersonalInfo { get => _personalInfo; set { _personalInfo = value; OnPropertyChanged(nameof(PersonalInfo)); } } public SettingPageViewModel() { LoadPersonalInfo(); } private void LoadPersonalInfo() { var personalInfoJson = Preferences.Get("PersonalInfo", string.Empty); if (!string.IsNullOrEmpty(personalInfoJson)) { Debug.WriteLine("Loading personal info for settings page..."); PersonalInfo = JsonConvert.DeserializeObject<PersonalInfo>(personalInfoJson); } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
2. 绑定设置页面ViewModel
在设置页面XAML根元素中添加绑定上下文:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:viewModels="clr-namespace:fitnessStudioMobileApp.ViewModels" x:Class="fitnessStudioMobileApp.Views.SettingPage"> <ContentPage.BindingContext> <viewModels:SettingPageViewModel /> </ContentPage.BindingContext> <!-- 原有页面内容 --> </ContentPage>
3. 修正ListView绑定错误
设置页面的SfListView绑定的PersonalInfo是单个对象,但ListView需要集合类型,有两种修正方式:
方式一:改为单个数据展示(更适合个人信息)
替换原有ListView为普通布局,直接绑定单个对象的属性:
<Grid Grid.Row="1" BackgroundColor="Azure"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="1"/> <RowDefinition Height="Auto"/> <RowDefinition Height="1"/> <RowDefinition Height="Auto"/> <RowDefinition Height="1"/> <RowDefinition Height="Auto"/> <RowDefinition Height="1"/> </Grid.RowDefinitions> <Frame Grid.Row="0" Padding="{OnPlatform 0}" CornerRadius="0" BorderColor="Transparent" BackgroundColor="{StaticResource FrameBackgroundColor}" HeightRequest="{OnPlatform 80}"> <Label Text="{Binding PersonalInfo.FullName}" TextColor="{StaticResource ActiveButtonTextColor}" VerticalOptions="Center" LineBreakMode="WordWrap" FontFamily="WorkSansMedium" FontSize="{OnPlatform 18}" Padding="{OnPlatform 15}"/> </Frame> <BoxView Grid.Row="1" Color="{StaticResource Gray400}" HeightRequest="{OnPlatform 1}"/> <Frame Grid.Row="2" Padding="{OnPlatform 0}" CornerRadius="0" BorderColor="Transparent" BackgroundColor="{StaticResource FrameBackgroundColor}" HeightRequest="{OnPlatform 80}"> <Label Text="{Binding PersonalInfo.Email}" TextColor="{StaticResource ActiveButtonTextColor}" VerticalOptions="Center" LineBreakMode="WordWrap" FontFamily="WorkSansMedium" FontSize="{OnPlatform 18}" Padding="{OnPlatform 15}"/> </Frame> <BoxView Grid.Row="3" Color="{StaticResource Gray400}" HeightRequest="{OnPlatform 1}"/> <Frame Grid.Row="4" Padding="{OnPlatform 0}" CornerRadius="0" BorderColor="Transparent" BackgroundColor="{StaticResource FrameBackgroundColor}" HeightRequest="{OnPlatform 80}"> <Label Text="{Binding PersonalInfo.PhoneNumber}" TextColor="{StaticResource ActiveButtonTextColor}" VerticalOptions="Center" LineBreakMode="WordWrap" FontFamily="WorkSansMedium" FontSize="{OnPlatform 18}" Padding="{OnPlatform 15}"/> </Frame> <BoxView Grid.Row="5" Color="{StaticResource Gray400}" HeightRequest="{OnPlatform 1}"/> <Frame Grid.Row="6" Padding="{OnPlatform 0}" CornerRadius="0" BorderColor="Transparent" BackgroundColor="{StaticResource FrameBackgroundColor}" HeightRequest="{OnPlatform 80}"> <Label Text="{Binding PersonalInfo.HomeAddress}" TextColor="{StaticResource ActiveButtonTextColor}" VerticalOptions="Center" LineBreakMode="WordWrap" FontFamily="WorkSansMedium" FontSize="{OnPlatform 18}" Padding="{OnPlatform 15}"/> </Frame> <BoxView Grid.Row="7" Color="{StaticResource Gray400}" HeightRequest="{OnPlatform 1}"/> </Grid>
方式二:保留ListView,转为集合绑定
修改SettingPageViewModel添加集合属性:
using System.Collections.ObjectModel; // 在ViewModel中添加 private ObservableCollection<PersonalInfo> _personalInfoList; public ObservableCollection<PersonalInfo> PersonalInfoList { get => _personalInfoList; set { _personalInfoList = value; OnPropertyChanged(nameof(PersonalInfoList)); } } // 修改LoadPersonalInfo方法 private void LoadPersonalInfo() { var personalInfoJson = Preferences.Get("PersonalInfo", string.Empty); if (!string.IsNullOrEmpty(personalInfoJson)) { Debug.WriteLine("Loading personal info for settings page..."); var personalInfo = JsonConvert.DeserializeObject<PersonalInfo>(personalInfoJson); PersonalInfoList = new ObservableCollection<PersonalInfo> { personalInfo }; } }
然后更新ListView的绑定:
ItemsSource="{Binding PersonalInfoList}"
4. 修复注册页面手机号绑定
注册页面的phoneNumberEntry未绑定ViewModel属性,添加双向绑定:
<editors:SfMaskedEntry x:Name="phoneNumberEntry" Placeholder="0123456789" MaskType="RegEx" Mask="" PlaceholderColor="{StaticResource BlurTextColor}" TextColor="{StaticResource NormalTextColor}" FontFamily="WorkSansRegular" FontSize="16" Text="{Binding PhoneNumber, Mode=TwoWay}"/>
内容的提问来源于stack exchange,提问作者Alfred Chua
相关产品推荐
相关产品推荐

