簡體   English   中英

Xamarin.Forms使用ViewModel導航到另一頁

[英]Xamarin.Forms Navigate to another page using ViewModel

我有幾個ContentPage,並且我想單擊頁面中的某個元素從一個導航到另一個。 我有我的ViewModel類:

 class JumpVM : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private INavigation _navigation;

        public ICommand NewPage
        {
            get
            {
                return new Command(async () =>
                {
                    await _navigation.PushAsync(new MySettingsPage());
                });
            }
        }

        public JumpVM() { }

        public JumpVM(INavigation navitation)
        {
            _navigation = navitation;
        }
    }

這是我的頁面之一(為了節省空間,我只放置了相關代碼):

BindingContext = new JumpVM(this.Navigation);

....

 Image fbInvite = new Image
            {
                Source = ImageSource.FromResource(Constants.ASSETLOCATION + ".facebookInviteIcon.png"),
                HorizontalOptions = LayoutOptions.Center
            };
            fbInvite.GestureRecognizers.Add(new TapGestureRecognizer(sender =>
                {
                    //navigation in the method below
                    FaceboonInviteFriends();
                    fbInvite.Opacity = 0.8;
                    fbInvite.FadeTo(1);
                }));

我想在單擊圖像時執行JumpVM類中的Command並導航到那里的頁面。 我怎樣才能做到這一點?

這是在ViewModel概念中將一頁導航到另一頁的答案。

public ICommand NavigationList { get; set; }

NavigationList = new Command(GetListview);  

public void  GetListview()
{
   Xamarin.Forms.Application.Current.MainPage.Navigation.PushAsync(new ListViewPerson());
}

嘗試在FadeTo行之后添加以下行: ((JumpVM)BindingContext).NewPage.Execute(null)

如果使用的是ViewModels,則可以使用ICommand輕松實現。

namespace YourApp.ViewModels
{
    public class CurrentPageViewModel
    {
        public ICommand BackToPage  {get; private set; }

        public CurrentPageViewModel()
        {
            BackToPage = new Command(async () => {
              await  Application.Current.MainPage.Navigation.PushModalAsync(new MainPage());
            });
        }
    }
}

在您要訪問的頁面的ViewModel中,您需要按以下方式實現PopAsync。

namespace YourApp.ViewModels
{
    public class MainPageViewModel 
    {
        public ICommand BackToMain { get; private set; }

        public MainPageViewModel()
        {
            BackToMain = new Command(async () => {
                await Application.Current.MainPage.Navigation.PopAsync();
            });
        }
    }
}

還要記住,在當前頁面上的Views CodeBehind下都使用Bindings,並且要像這樣去。

namespace RealmApp1.Views
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            BindingContext = new MainPageViewModel();
        }      
    }
}

希望這對你有用! 有一個不錯的代碼!!!

這就是我所做的

我使用以下幫助程序類

https://gist.github.com/julesx/4a3b68ef7f7eda8572ae5755e3665d47

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM