Xamarin Forms 可绑定选择器 - 如何在 ViewModel 中获取所选项目

Xamarin Forms Bind-able Picker - How to get selected item in ViewModel

我正在使用 Xamarin 表单:2.3.4.247 棱镜库:6.3.0

以下是最新的Xamarin Forms中带有Bind-able Picker ass的代码: 查看

将我认为的(棱镜)行为注册为以下

xmlns:b="clr-namespace:Prism.Behaviors;assembly=Prism.Forms"

Picker 还显示 CountryCodes 的数据,这是一个 PickerItem

类型的列表
       <Picker  ItemsSource="{Binding CountryCodes}" Title="Select Country"  ItemDisplayBinding="{Binding Name}">
            <Picker.Behaviors>
                <b:EventToCommandBehavior EventName="SelectedIndexChanged" Command="{Binding ItemTappedCommand}" EventArgsParameterPath="Item" />
            </Picker.Behaviors>
        </Picker>

在相应的视图模型中,我将命令定义为

public DelegateCommand<PickerItem> ItemTappedCommand { get; }

并且在构造函数中:

ItemTappedCommand = new DelegateCommand<PickerItem>(OnCountryPickerTapCommandExecuted);

委托功能如下:

private void OnCountryPickerTapCommandExecuted(PickerItem item)
{
    SelectedCountryCode = item.Code;//some property I want it to assign
}

问题是选择器绑定正确,但是当selecting/changing选择时没有任何反应:

我是不是错过了什么,棱镜?

您不需要事件来控制行为。您可以在 中查看有关如何使用选取器的信息。该示例未使用 Prism,但其工作方式完全相同。

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
             xmlns:local="clr-namespace:PickerDemo" 
             x:Class="PickerDemo.PickerDemoPage">
    <ContentPage.BindingContext>
        <local:PickerDemoPageViewModel />
    </ContentPage.BindingContext>
    <StackLayout Padding="10,20">
        <!-- Picker with explicitly set values in XAML -->
        <Picker SelectedItem="{Binding SelectedItem}">
            <Picker.Items>
                <x:String>Item 1</x:String>
                <x:String>Item 2</x:String>
            </Picker.Items>
        </Picker>
        <Label Text="{Binding SelectedItem,StringFormat='You Selected: {0}'}" />

        <!-- Picker with Dynamically set values -->
        <Picker ItemsSource="{Binding SomeCollection}" SelectedItem="{Binding AnotherItem}" />
        <Label Text="{Binding AnotherItem,StringFormat='You picked: {0}'}" />

        <!-- Date Picker using a custom display format -->
        <DatePicker Date="{Binding SomeDate}" Format="MMMM dd, yyyy" />
        <Label Text="{Binding SomeDate,StringFormat='{0:dd MMMM, yyyy}'}" />
    </StackLayout>

</ContentPage>

编辑:

没有 SeletedItemChanged 事件,只有 SelectedItemIndexChanged 事件,这有点毫无意义。然而,在 Prism 6.3 中,您可以执行以下操作:

public class FooBar : BindableBase
{
    private INavigationService _navigationService { get; }

    public FooBar(INavigationService navigationService)
    {
        _navigationService = navigationService;
    }

    private string _foo;
    public string Foo
    {
        get { return _foo; }
        set { SetProperty(ref _foo, value, OnFooChanged);}
    }

    private async void OnFooChanged() => 
        await _navigationService.NavigateAsync("SomePage", new NavigationParameters() { { "foo", Foo } });
}