【问题标题】:Make a object/variable available globally in the shell xamarin forms使对象/变量在 shell xamarin 表单中全局可用
【发布时间】:2026-01-31 10:55:02
【问题描述】:

我用的是xamarin forms shell,在页脚我有一个ContentView [UserView],Bindcontext到LoginViewModel,登录成功。

<Shell 
...
    <Shell.FlyoutFooter>
        <control:UserView/>
    </Shell.FlyoutFooter>
...

我想让对象 [User] 对其他内容视图通用,通过参数序列化非常昂贵:

await Shell.Current.GoToAsync($"SomePage?serialized={Uri.EscapeDataString(serialized)}");
await Shell.Current.GoToAsync($"OthersLotsPages?serialized={Uri.EscapeDataString(serialized)}");

是否可以将这个对象 [User] 作为服务或类似的东西提供,所有页面都可以访问它而无需序列化?如果可能,最好的方法是什么?

LoginViewModel.cs

    public User _user { get; set; }
    public User UserTemp
    {
        get { return _user ; }
        set
        {
           _user = value;
           OnPropertyChanged("UserTemp");
        }
    }

...

private async void Login()
{
...
      UserTemp = await UserService.Login(username, password); //Let UserTemp accessible for other all contentpages after login success
...
}

图片 1

图片 2

图 3

【问题讨论】:

  • 使其成为您的 App 类的属性

标签: c# xamarin xamarin.forms


【解决方案1】:

Application 子类有一个静态的Properties 字典,可用于存储数据,特别是用于OnStartOnSleepOnResume 方法。可以使用 Application.Current.Properties 从 Xamarin.Forms 代码中的任何位置访问它。

Properties 字典使用字符串键并存储对象值。

你可以像这样保存数据:

Application.Current.Properties ["User"] = YourUser;

那么您可以在页面的OnAppearing() 方法中获取它:

protected override void OnAppearing()
 {
    base.OnAppearing();
    if (Application.Current.Properties.ContainsKey("User"))
    {
        User user= (User)Application.Current.Properties["user"];
    }
}

Properties dictionary 可以看的越多。

【讨论】: