【问题标题】:Switching through different Pages in MVVM在 MVVM 中切换不同的页面
【发布时间】:2016-10-28 18:07:34
【问题描述】:

我正在尝试在我的 Xamarin MVVM 项目中实现切换不同页面的功能。我有三个文件夹——“模型”、“视图”和“视图模型”。 “视图”包含“主视图”,其作用是显示其他视图。

MainView.xaml:

<?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="KeepFit.Views.MainView">

  <ContentPresenter x:Name="ContentArea" Content="{Binding CurrentView}"/>

</ContentPage> 

MainView.xaml.cs:

public partial class MainView : ContentPage
{
    public MainView()
    {
        InitializeComponent();

        BindingContext = new MainViewModel();
    }
}

如您所见,“MainView”绑定到“MainViewModel”类。

MainViewModel.cs:

public class MainViewModel : INotifyPropertyChanged
    {
        public Command SwitchViewsCommand { get; private set; }

        public MainViewModel()
        {
            SwitchViewsCommand = new Command((parameter) =>
            CurrentView = (ContentPage)Activator.CreateInstance(parameter as Type)); 
            CurrentView = new HomeView();
        }

        private ContentPage _currentView;
        public ContentPage CurrentView
        {
            get
            {
                return _currentView;
            }
            set
            {
                if (value != _currentView)
                {
                    _currentView = value;
                    OnPropertyChanged("CurrentView");
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName]
        string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

CurrentView 在构造函数中设置为我的 HomeView(假设它是默认的 ContentPage)。它绑定到 ContentPresenter,因此它应该在我的应用程序运行时开始时可见。但事实并非如此。

我注意到 ContentPresenter 期望 Xamarin.Forms.View 对象作为“内容” - 我的视图继承自 Xamarin.Forms.ContentPage。但是,例如,如果我将它们更改为 ContentViews - 我将无法为它们设置 BindingContext。谁能解释我做错了什么?

【问题讨论】:

    标签: c# mvvm xamarin


    【解决方案1】:

    你要试试这个?

     async void butonClick(object sender, EventArgs e)
       {
            await Navigation.PushAsync(new EntryPageCode());
        }
    

    您的视图实例位于“EntryPageCode”位置,好的。 试试这个并告诉我,如果你的工作适合你。

    【讨论】:

      猜你喜欢
      • 2013-08-17
      • 2019-03-22
      • 2023-03-20
      • 2020-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-15
      • 1970-01-01
      相关资源
      最近更新 更多