【发布时间】: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。谁能解释我做错了什么?
【问题讨论】: