【发布时间】:2017-11-02 15:31:47
【问题描述】:
我正在使用 Xaml 为 UI 进行 Xamarin 表单项目的数据绑定。 到目前为止,它非常简单:
XAML:
<?xml version="1.0" encoding="utf-8" ?>
xmlns:viewModels="clr-namespace:Watson.ViewModels;assembly=Watson"
x:Class="Watson.Views.DeviceCheck">
<ContentPage.BindingContext>
<viewModels:DeviceCheckViewModel/>
</ContentPage.BindingContext>
<!--<ActivityIndicator Color="Red" IsRunning="True"
x:Name="loadingScreen"/>-->
<StackLayout>
<Label Text="Checking Device.."/>
<Button Text="page nav"
Command="{Binding NextButton}"></Button>
</StackLayout>
背后的代码:
namespace Watson.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class DeviceCheck:ContentPage
{
private DeviceCheckViewModel viewModel;
public DeviceCheck() {
InitializeComponent();
BindingContext = viewModel = new DeviceCheckViewModel(this.Navigation);
}// end of constructor
}// end of class
}// end of namespace
这是尝试绑定到视图模型并使用绑定命令在单击按钮时转到另一个页面。
我得到的错误是“字典中不存在给定的键”,这是在尝试构建时。我已将问题隔离到一行:<viewModels:DeviceCheckViewModel/>
我不知道为什么会出现这个错误。
这是视图模型:
namespace Watson.ViewModels
{
public class DeviceCheckViewModel: INotifyPropertyChanged
{
public INavigation Navigation { get; set; }
public ICommand NextButton { protected set; get; }
public DeviceCheckViewModel(INavigation navigation)
{
this.Navigation = navigation;
this.NextButton = new Command(async () => await GotoNextPage());
}
public async Task GotoNextPage()
{
await Navigation.PushAsync(new RegisterDevice());
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
}
}
我追求这条路线的原因是坚持 MVVM 架构。 所以将页面导航放在代码后面并不是一个真正的选择。 也请注意,所有模型、视图模型和视图都在同名的文件夹结构中。
任何帮助将不胜感激。
【问题讨论】: