【问题标题】:Xamarin Pass data from a viewModel to anotherXamarin 将数据从 viewModel 传递到另一个
【发布时间】:2020-08-25 14:32:33
【问题描述】:

我是 Xamarin 的新手,无法将数据从一个 ViewModel 传递到另一个。 我尝试了很多东西,但没有任何效果。 那么到目前为止我做了什么

在我的 LoginViewModel 上,我有这段代码可以从数据库中获取信息

 CRUD crud = new CRUD();
 UserLogin = crud.Login(UserName, Password);       
 Application.Current.MainPage = new AppShell();
 await Shell.Current.GoToAsync($"//{nameof(HomePage)}?UserLogin={UserLogin}");

在我的主页上,我尝试了很多东西。 这是我现在主页上的内容:ContentPage

    {
        public HomePage()
        {
            InitializeComponent();
        }
        public HomePage(List<User> UserLogin)
        {
            
            this.BindingContext = new HomeViewModel(UserLogin);
        }
      
    }

我尝试移动 InitializeCompognent(),删除它,删除基本构造函数,但我有空白页或错误。这是我加载页面的唯一方法。 在 HomeViewModel 我有这个代码

 public class HomeViewModel : BaseViewModel
    {
        public List<User> UserLogin { get;}

        public HomeViewModel() { }

        public HomeViewModel(List<User> Users)
        {
            Title = "Acceuil";
            UserLogin = Users;
        }
    }

当我调试时,我在登录视图模型中停止等待 Shell.Curent...我检查 HomeViewModel UserLogin 并且我有我的数据。但它似乎是在页面加载后将其清除。 有人可以帮我在 HomeViewModel 页面上获取数据吗? 谢谢。 Jc

【问题讨论】:

  • 所以如果我明白没有办法轻松做到这一点?我不明白。 C#当然是面向对象的,没有一些复杂的技巧我不能传递一个对象??
  • 有很多方法可以接近它。用户登录数据可以存储为 App 类的属性,因此可以普遍使用。如果您不使用 shell 导航,则可以更好地控制导航时数据的传递方式。或者有一个与其他问题相关联的项目可以使用 Shell

标签: c# android ios xamarin


【解决方案1】:

pass data in shell的文档中:

为了接收数据,代表被导航页面的类 to,或页面的 BindingContext 的类,必须用 每个查询参数的QueryPropertyAttribute

在您的主页中,它应该具有如下属性:

[QueryProperty("myUserLogin", "UserLogin")]
public partial class HomePage : ContentPage
{
    public List<User> myUserLogin { get; set; }

    public HomePage()
    {
        InitializeComponent();
    }
}

并且您不应该删除 InitializeCompognent(),因为它负责在 Xaml 中加载代码。

第二种解决方案

在 App 类中声明一个属性:

public partial class App : Application
{
    public static List<User> UserLogin { get; set; }

    public App()
    {
        InitializeComponent();

        MainPage = new AppShell();
    }
}

然后在你的LoginViewModel,获取数据:

 App.UserLogin = crud.Login(UserName, Password);       

你不需要传递给HomePage,在HomePage中,你可以通过:

public HomePage()
{
    InitializeComponent();

    List<User> myUserData = App.UserLogin;
}

【讨论】:

    猜你喜欢
    • 2022-11-25
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多