鉴于字典Xamarin表单中不存在键

use*_*961 4 c# xaml xamarin

我正在使用Xaml为UI处理Xamarin表单项目的数据绑定.到目前为止它非常简单:

XAML:

<?xml version="1.0" encoding="utf-8" ?>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

背后的代码:

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
Run Code Online (Sandbox Code Playgroud)

这是尝试绑定到视图模型并使用绑定命令在按钮单击时转到另一个页面.我得到的错误是"给定的密钥不在字典中",这是在尝试构建时.我把问题隔离到了这一行:<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));
    }
}
}
Run Code Online (Sandbox Code Playgroud)

我追求这条路线的原因是坚持MVVM架构.因此,将页面导航放在后面的代码中并不是一个真正的选择.同样只是一个注释,所有模型,视图模型和视图都在具有相同名称的文件夹结构中.

任何帮助,将不胜感激.

小智 12

您在代码中设置绑定上下文:

BindingContext = viewModel = new DeviceCheckViewModel(this.Navigation);
Run Code Online (Sandbox Code Playgroud)

因此,也没有必要采用xaml方式.这也创建了一个实例DeviceCheckViewModel并将其设置为绑定上下文:

<ContentPage.BindingContext>
    <viewModels:DeviceCheckViewModel/>
</ContentPage.BindingContext>
Run Code Online (Sandbox Code Playgroud)

但是,因此它需要一个无参数的构造函数.这可能是你获得超越的原因.