1

我有一个自定义选择器。我需要在选择器的选择更改时调用 API,并且实现必须仅在 MVVM 中。DistanceDropdown 是选择器的 x:Name。

<custom:MyPicker.Behaviors>
             <behaviors:EventToCommandBehavior EventName="SelectedIndexChanged"
                                               Command="{Binding Path=BindingContext.DistanceChangedCommand,Source={x:Reference DistanceDropdown}}"></behaviors:EventToCommandBehavior>
   </ccustom:MyPicker.Behaviors>

并且 DistanceChangedCommand 有一个方法

DistanceChangedCommand = new Command<object>(async (x) => await DistanceChangedAction(x as SelectionChangedEventArgs));

该方法被命中,但参数为空

private async Task DistanceChangedAction(SelectionChangedEventArgs selectionChangedEventArgs)
        {
            await Task.CompletedTask;
        }

我怎么了?我也试过了CommandParameter={Binding}

4

1 回答 1

0

Picker View的事件SelectedIndexChanged具有如下委托处理程序签名:private void Picker_SelectedIndexChanged(object sender, EventArgs e). 所以你的命令应该转换为EventArgs而不是SelectionChangedEventArgs.

更好的方法是利用CommndParameter

<Picker x:Name="DistanceDropdown" ...>
 <Picker.Behaviors>
          <xct:EventToCommandBehavior
                  EventName="SelectedIndexChanged"
                  Command="{Binding ItemTappedCommand}"
                  CommandParameter="{Binding Source={x:Reference DistanceDropdown},
                                             Path=SelectedIndex}"/>
    </Picker.Behaviors>

你会期望一个类型的参数int

DistanceChangedCommand = new Command<int>(async (x) => await DistanceChangedAction(x);

private async Task DistanceChangedAction(int selectedIndex)
        {
            await Task.CompletedTask;
            
        }

更好的是,您可以使用AsyncCommand(也附带 Xamarin-Community-Toolkit):

public ICommand DistanceChangedCommand { get; private set; } 
                                      = new AsyncCommand<int>(selectedIndex
                                            => await Task.CompletedTask);
于 2021-02-22T13:14:44.960 回答