如何将登录页用户信息传递到主页,及解决User.Picture非静态引用报错
Error An object reference is required for the non-static field, method, or property 'User.Picture'
错误原因
- 你定义的
User类中Picture、Id、Name等属性都是实例属性,必须通过User类的实例对象访问,不能直接用类名User调用 - 你在LoginPage中反序列化得到的
user实例没有传递到HomePage,HomePage无法直接获取登录后的用户数据 - 额外注意:
User类中定义的ID字段属性名为Id(首字母小写i),你代码中写的User.ID大小写不匹配,也会触发报错
修复方案
方案1:构造函数传参(适合你注释中的页面跳转逻辑)
- 修改HomePage构造函数,增加User类型参数接收登录用户实例
public partial class HomePage : ContentPage { public HomePage(User user) { InitializeComponent(); PictureImage.Source = user.Picture; IdLabel.Text = user.Id; NameLabel.Text = user.Name; // 其余逻辑保持不变 } }
- 修改LoginPage跳转逻辑,把获取到的user实例传入HomePage
if (user != null) { App.Current.MainPage = new NavigationPage(new HomePage(user)); }
方案2:全局静态变量存储(适合Shell路由跳转场景)
- 修改AuthenticationState类,增加静态属性存储当前登录用户
public class AuthenticationState { public static OAuth2Authenticator Authenticator; public static User CurrentLoginUser { get; set; } }
- LoginPage获取到用户实例后先赋值给全局静态属性
if (user != null) { AuthenticationState.CurrentLoginUser = user; var route = $"{ nameof(HomePage)}"; await Shell.Current.GoToAsync(route); }
- HomePage直接访问全局静态属性即可
public HomePage() { InitializeComponent(); PictureImage.Source = AuthenticationState.CurrentLoginUser.Picture; IdLabel.Text = AuthenticationState.CurrentLoginUser.Id; NameLabel.Text = AuthenticationState.CurrentLoginUser.Name; }
内容的提问来源于stack exchange,提问作者Star Gates
相关产品推荐
相关产品推荐

