I am working on xamarin.form cross-platform application , i want to navigate from one page to another on button click. As i cannot do Navigation.PushAsync(new Page2());
I looked into this, and it really depends on how you want to handle your navigation. Do you want your view models to handle your navigation or do you want your views. I found it easiest to have my views handle my navigation so that I could choose to have a different navigation format for different situations or applications. In this situation, rather than using the command binding model, just use a button clicked event and add the new page to the navigation stack in the code behind.
Change your button to something like:
<StackLayout>
<Button Clicked="Button_Clicked"></Button>
</StackLayout>
And in your code behind, implement the method and do the navigation there.
public void Button_Clicked(object sender, EventArgs e)
{
Navigation.PushAsync(new Page2());
}
If you are looking to do viewmodel based navigation, I believe there is a way to do this with MvvmCross, but I am not familiar with that tool.
Passing INavigation through VM constructor is a good solution indeed, but it can also be quite code-expensive if you have deep nested VMs architecture.
Wrapping INavigation with a singleton, accesible from any view model, is an alternative:
NavigationDispatcher Singleton:
public class NavigationDispatcher
{
private static NavigationDispatcher _instance;
private INavigation _navigation;
public static NavigationDispatcher Instance =>
_instance ?? (_instance = new NavigationDispatcher());
public INavigation Navigation =>
_navigation ?? throw new Exception("NavigationDispatcher is not initialized");
public void Initialize(INavigation navigation)
{
_navigation = navigation;
}
}
Initializing in App.xaml.cs:
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new MainPage());
NavigationDispatcher.Instance.Initialize(MainPage.Navigation);
}
Using in any ViewModel:
...
private async void OnSomeCommand(object obj)
{
var page = new OtherPage();
await NavigationDispatcher.Instance.Navigation.PushAsync(page);
}
...
A simple way is
this.ContinueBtnClicked = new Command(async()=>{
await Application.Current.MainPage.Navigation.PushAsync(new Page2());
});
One way is you can pass the Navigation through the VM Constructor. Since pages inherit from VisualElement
, they directly inherit the Navigation
property.
Code behind file:
public class SignIn : ContentPage
{
public SignIn(){
InitializeComponent();
// Note the VM constructor takes now a INavigation parameter
BindingContext = new LocalAccountViewModel(Navigation);
}
}
Then in your VM, add a INavigation
property and change the constructor to accept a INavigation
. You can then use this property for navigation:
public class LocalAccountViewModel : INotifyPropertyChanged
{
public INavigation Navigation { get; set;}
public LocalAccountViewModel(INavigation navigation)
{
this.Navigation = navigation;
this.ContinueBtnClicked = new Command(async () => await GotoPage2());
}
public async Task GotoPage2()
{
/////
await Navigation.PushAsync(new Page2());
}
...
Note an issue with your code that you should fix: The GoToPage2()
method must be set async
and return the Task
type. In addition, the command will perform an asynchronous action call. This is because you must do page navigation asychronously!
Hope it helps!
From your VM
public Command RegisterCommand
{
get
{
return new Command(async () =>
{
await Application.Current.MainPage.Navigation.PushAsync(new RegisterNewUser());
});
}
}
I racked my brains on this a few days hitting the same hurdle when I switched to Xamarin development.
So my answer is to put the Type of the page in the Model but not restricting the View or the ViewModel to work with it also if one so chooses. This keeps the system flexible in that it does not tie up the Navigation via hard-wiring in the view or in the code-behind and therefore it is far more portable. You can reuse your models across the projects and merely set the type of the Page it will navigate to when such circumstance arrive in the other project.
To this end I produce an IValueConverter
public class PageConverter : IValueConverter
{
internal static readonly Type PageType = typeof(Page);
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Page rv = null;
var type = (Type)value;
if (PageConverter.PageType.IsAssignableFrom(type))
{
var instance = (Page)Activator.CreateInstance(type);
rv = instance;
}
return rv;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var page = (Page)value;
return page.GetType();
}
}
And an ICommand
public class NavigateCommand : ICommand
{
private static Lazy<PageConverter> PageConverterInstance = new Lazy<PageConverter>(true);
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
var page = PageConverterInstance.Value.Convert(parameter, null, null, null) as Page;
if(page != null)
{
Application.Current.MainPage.Navigation.PushAsync(page);
}
}
}
Now the Model may have an assignable Type for a page, therefore it can change, and the page can be different between your device types (e.g Phone, Watch, Android, iOS). Example:
[Bindable(BindableSupport.Yes)]
public Type HelpPageType
{
get
{
return _helpPageType;
}
set
{
SetProperty(ref _helpPageType, value);
}
}
And an example of it's use then in Xaml.
<Button x:Name="helpButton" Text="{Binding HelpButtonText}" Command="{StaticResource ApplicationNavigate}" CommandParameter="{Binding HelpPageType}"></Button>
And for the sake of completeness the resource as defined in App.xaml
<Application.Resources>
<ResourceDictionary>
<xcmd:NavigateCommand x:Key="ApplicationNavigate" />
</ResourceDictionary>
</Application.Resources>
P.S. While the Command pattern generally should use one instance for one operation, in this case I know it is very safe to reuse the same instance across all controls and since it is for a wearable I want to keep things lighter than normal hence defining a single instance of the NavigationCommand in the App.xaml.