Xamarin.Forms使用ViewModel导航到另一个页面

时间:2015-02-26 10:21:30

标签: c# mvvm xamarin xamarin.forms

我有几个ContentPages,我想通过点击页面中的元素从一个到另一个。我有我的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并导航到那里的页面。我怎么能这样做?

3 个答案:

答案 0 :(得分:6)

这是在ViewModel概念中将一个页面导航到另一个页面的答案。

[[tuple(map(tuple, x.reshape(2,2))) for x in a]]

答案 1 :(得分:1)

尝试在FadeTo行后添加以下行: ((JumpVM)BindingContext).NewPage.Execute(null)

答案 2 :(得分:0)

如果使用的是ViewModels,则可以使用ICommand轻松实现。

react-native run-android

在您要访问的页面的ViewModel中,您需要按以下方式实现PopAsync。

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

还请记住在当前页面的Views CodeBehind上都使用绑定,并且您要像这样去做。

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

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

希望它对您有用! 有一个不错的代码!!!

相关问题