Issue
I'm new to Xamarin and I'm not able to pass data from one ViewModel to another. I try a lot of thing but nothing work. So what's ive done so far
On my LoginViewModel I have this code to get info from the database
CRUD crud = new CRUD();
UserLogin = crud.Login(UserName, Password);
Application.Current.MainPage = new AppShell();
await Shell.Current.GoToAsync($"//{nameof(HomePage)}?UserLogin={UserLogin}");
On My HomePage I try a lot of thing. This is what I have now on the homepage: ContentPage
{
public HomePage()
{
InitializeComponent();
}
public HomePage(List<User> UserLogin)
{
this.BindingContext = new HomeViewModel(UserLogin);
}
}
I try to move the InitializeCompognent(), Remove it, remove the base constructor but I have blank page or a error. That's the only way I get a page loaded. On the HomeViewModel I have this code
public class HomeViewModel : BaseViewModel
{
public List<User> UserLogin { get;}
public HomeViewModel() { }
public HomeViewModel(List<User> Users)
{
Title = "Acceuil";
UserLogin = Users;
}
}
When I debug I I stop in the Login view Model await Shell.Curent...I check the HomeViewModel UserLogin and I have my data. But it seem's to wipe it out when the page is loaded after. Can somebody help me having the data on the HomeViewModel page please. Thanks. Jc
Solution
In the document of pass data in shell:
To receive data, the class that represents the page being navigated to, or the class for the page's BindingContext, must be decorated with a
QueryPropertyAttribute
for each query parameter
In your HomePage, it should have a property like this:
[QueryProperty("myUserLogin", "UserLogin")]
public partial class HomePage : ContentPage
{
public List<User> myUserLogin { get; set; }
public HomePage()
{
InitializeComponent();
}
}
And you should not remove InitializeCompognent()
as it is responsible for loading codes in Xaml.
Second solution:
Declare a property in App class:
public partial class App : Application
{
public static List<User> UserLogin { get; set; }
public App()
{
InitializeComponent();
MainPage = new AppShell();
}
}
Then in your LoginViewModel
, get the data:
App.UserLogin = crud.Login(UserName, Password);
You don't need to pass it to HomePage, in the HomePage, you can get it by:
public HomePage()
{
InitializeComponent();
List<User> myUserData = App.UserLogin;
}
Answered By - nevermore
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.