简体   繁体   中英

Page Navigation using MVVM in Xamarin.Forms

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()); in ViewModel because it only possible in Code-Behid file. please suggest any way to do this?

Here is my View:

<?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="Calculator.Views.SignIn"
             xmlns:ViewModels="clr-namespace:Calculator.ViewModels;assembly=Calculator">
    
    <ContentPage.BindingContext>
        <ViewModels:LocalAccountViewModel/>
    </ContentPage.BindingContext>
    
    <ContentPage.Content>    
        <StackLayout>
            <Button Command="{Binding ContinueBtnClicked}" />    
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

Here is my ViewModel:

public class LocalAccountViewModel : INotifyPropertyChanged
{
    public LocalAccountViewModel()
    {
        this.ContinueBtnClicked = new Command(GotoPage2);
    }
        
    public void GotoPage2()
    {
        /////
    }
    
    public ICommand ContinueBtnClicked
    {
        protected set;
        get;
    }
    
    public event PropertyChangedEventHandler PropertyChanged;
    
    protected virtual void OnPropertyChanges([CallerMemberName] string PropertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
    }
}

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!

A simple way is

this.ContinueBtnClicked = new Command(async()=>{

    await Application.Current.MainPage.Navigation.PushAsync(new Page2());
});

From your VM

public Command RegisterCommand
        {
            get
            {
                return new Command(async () =>
                {
                    await Application.Current.MainPage.Navigation.PushAsync(new RegisterNewUser());
                });

            }
        }

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.

my approach based on principle every View can navigate to VM context based places of the app only:

In ViewModel i declare INavigationHandler interfeces like that:

public class ItemsViewModel : ViewModelBase
{
    public INavigationHandler NavigationHandler { private get; set; }


    // some VM code here where in some place i'm invoking
    RelayCommand<int> ItemSelectedCommand => 
        new RelayCommand<int>((itemID) => { NavigationHandler.NavigateToItemDetail(itemID); });


    public interface INavigationHandler
    {
        void NavigateToItemDetail(int itemID);
    }
}

And assign code-behind class as INavigationHandler for ViewModel:

public class ItemsPage : ContentPage, ItemsViewModel.INavigationHandler
{
    ItemsViewModel viewModel;

    public ItemsPage()
    {
        viewModel = Container.Default.Get<ItemsViewModel>();
        viewModel.NavigationHandler = this;
    }


    public async void NavigateToItemDetail(int itemID)
    {
        await Navigation.PushAsync(new ItemDetailPage(itemID));
    }
}

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);
        }
 ...

decided to add two ways to pass Page instance to viewmodel which you can use later for navigation, displaying alerts. closing page and so on.

1. if you can pass it with command parameter

in view model:

public ICommand cmdAddRecord { get; set; }

viewmodel constructor

cmdAddRecord = new Command<ContentPage>(AddRecord);

somewhere in viewmodel

    void AddRecord(ContentPage parent)
    {
        parent.Navigation.Whatever
    }

XAML

header

            x:Name="thisPage"

usage

 <ToolbarItem IconImageSource="{StaticResource icAdd}"  Command="{Binding cmdAddRecord}"  CommandParameter="{Binding ., Source={x:Reference thisPage}}" />

2. started using this in my base class for viewmodels

viewmodel

public class cMyBaseVm : BindableObject

...

public static BindableProperty ParentProperty = BindableProperty.Create("Parent", typeof(ContentPage), typeof(cMyBaseVm), null, BindingMode.OneWay);

...

   public ContentPage Parent
    {
        get => (ContentPage)GetValue(ParentProperty);
        set => SetValue(ParentProperty, value);
    }

XAML

        xmlns:viewModels="clr-namespace:yournamespace.ViewModels"
        x:Name="thisPage"

and here we go

<ContentPage.BindingContext>
    <viewModels:cPetEventsListVm Parent="{Binding ., Source={x:Reference thisPage}}" />
</ContentPage.BindingContext>

child viewmodel

public class cPetEventsListVm : cMyBaseVm

and now, all around child view model we can use Page like Parent.DisplayAlert , or Parent.Navigation.PushAsync etc we may even close page now from view model with Parent.PopAsync ();

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 (eg 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>

PS 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM