Xamarin.forms Picker Xamarin中的异常

Xamarin.forms Picker Xamarin中的异常,xamarin.forms,Xamarin.forms,我是xamarin的新手。我曾尝试实现Picker,项目构建很好,但它始终给我以下运行时异常: System.ArrayTypeMismatchException:“试图以与数组不兼容的类型访问元素。” 我在这里附上我的xaml、代码隐藏和异常截图。希望有人能帮忙 这是xaml部分: <Label Text="{Binding Source={x:Reference picker}, Path=SelectedItem}"/>

我是xamarin的新手。我曾尝试实现Picker,项目构建很好,但它始终给我以下运行时异常:

System.ArrayTypeMismatchException:“试图以与数组不兼容的类型访问元素。” 我在这里附上我的xaml、代码隐藏和异常截图。希望有人能帮忙

这是xaml部分:

          <Label Text="{Binding Source={x:Reference picker}, 
          Path=SelectedItem}"/> 

                        <Label x:Name="hasarnedeniLabel"></Label>
                        <Picker x:Name="picker" Title="Select a monkey">
                            <Picker.ItemsSource>
                                <x:Array Type="{x:Type x:String}">
                                    <x:String>Baboon</x:String>
                                    <x:String>Capuchin Monkey</x:String>
                                    <x:String>Blue Monkey</x:String>
                                    <x:String>Squirrel Monkey</x:String>
                                    <x:String>Golden Lion Tamarin</x:String>
                                    <x:String>Howler Monkey</x:String>
                                    <x:String>Japanese Macaque</x:String>
                                </x:Array>
                            </Picker.ItemsSource>
                        </Picker>

您使用的是哪个版本的Xamarin.Forms

在Xamarin.Forms 2.3.4之前,不需要在XAML中声明数组类型:

<Picker x:Name="picker" Title="Select a monkey">
  <Picker.ItemsSource>
    <x:String>Baboon</x:String>
    <x:String>Capuchin Monkey</x:String>
    <x:String>Blue Monkey</x:String>
    <x:String>Squirrel Monkey</x:String>
    <x:String>Golden Lion Tamarin</x:String>
    <x:String>Howler Monkey</x:String>
    <x:String>Japanese Macaque</x:String>
  </Picker.ItemsSource>
一般来说,您应该使用MVVM。因此,将有一个VM将您的数组绑定到UI控件。下面是一个可以帮助您理解MVVM的示例

以下是一个例子:

<Picker
  Title="Select a monkey"
  ItemsSource="{Binding Monkeys}" />
为了使其正常工作,您还需要为包含此选择器控件的页面创建ViewModel,并将页面的BindingContext设置为ViewModel:

public MainPage()
{
  InitializeComponent();
  this.BindingContext = new MainPageViewModel(); /* Which should contain public List<string> Monkeys { get; set; } */
}
或者,您可以在XAML中设置BindingContext:

<ContentPage
  xmlns:vm="clr-namespace:YourProject.ViewModelsNamespace"
..>
  <ContentPage.BindingContext>
    <vm:MainPageViewModel />
  </ContentPage.BindingContext>
</ContentPage>

代码看起来不错。这是整个页面的内容吗?
<ContentPage
  xmlns:vm="clr-namespace:YourProject.ViewModelsNamespace"
..>
  <ContentPage.BindingContext>
    <vm:MainPageViewModel />
  </ContentPage.BindingContext>
</ContentPage>