我有一个自定义选择器。我需要在选择器的选择更改时调用 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}
。
最佳答案
Picker View 的事件 SelectedIndexChanged
具有如下委托(delegate)处理程序签名: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);
关于c# - 使用 EventToCommandBahavior 的 Xamarin 表单选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66315758/