3
I recently started studying Xamarin Forms. I have a question that can be clarified here: how to navigate between pages using MVVM? Navigation should be on vm or in the view?
Example
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="GeoMobile.Views.Login">
<StackLayout>
<Label Text="GEO Mobile" VerticalOptions="Center" HorizontalOptions="Center" />
<Entry Text="{Binding Email}" Placeholder="Email" />
<Entry Text="{Binding Senha}" Placeholder="Senha" />
<Button Text="Entrar" Command="{Binding Entrar}" />
<Button Text="Registrar" />
</StackLayout>
</ContentPage>
Login.Cs
public partial class Login : ContentPage
{
public Login()
{
InitializeComponent();
this.BindingContext = new LoginVM(Entrar);
}
public async void Entrar()
{
Navigation.InsertPageBefore(new Master__(), this);
await Navigation.PopAsync();
}
}
And in my vm:
public class LoginVM : ObservableBase
{
private string _email;
public string Email
{
get { return _email; }
protected set
{
_email = value;
OnPropertyChanged();
}
}
private string _senha;
public string Senha
{
get { return _senha; }
set
{
_senha = value;
OnPropertyChanged();
}
}
public Command Entrar { get; private set; }
private Action loginOk;
private void login()
{
//checagem antes de ir para a proxima pagina
loginOk();
}
public LoginVM(Action loginOk)
{
this.loginOk = loginOk;
Entrar = new Command(login);
}
}
I got the navigation by passing an action in the vm constructor, but I need to implement another navigation for the register button, but for that I would already have to pass another action in the constructor and I believe that this would not be a good practice.
If you put navigation in the vm, the software testing process will be difficult. What is the best way to get around the problem?
Great Brian, even had seen this video yesterday. Good show, exactly what I needed.
– samuel ferreira
Show! I recommend Prism as mvvm framework, it solves the navigation part brilliantly :)
– Angelo Belchior