Xamarin Forms Bind-able Picker - 如何在ViewModel中获取所选项目

时间:2017-05-31 10:42:00

标签: xamarin xamarin.forms prism

我正在使用Xamarin表格:2.3.4.247 棱镜图书馆:6.3.0

以下是最新Xamarin表格中具有Bind-able Picker屁股的代码: 查看

在我的视图中注册(prism)行为,如下

  

的xmlns:B =" CLR-名称空间:Prism.Behaviors;装配= 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; }

和In构造函数:

ItemTappedCommand = new DelegateCommand<PickerItem>(OnCountryPickerTapCommandExecuted);

委派的功能如下:

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

问题是选择器是否正确绑定,但是在选择/更改选择时没有任何事情发生:

我在棱镜中遗漏了什么吗?

1 个答案:

答案 0 :(得分:1)

您不应该需要一个事件来命令行为。关于如何使用拣货员,您可以看到answer。这个例子不是使用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 } });
}