Reputation: 55
I have a custom picker. I need to call an API on selection changed of the picker and the implementation must be only in MVVM. DistanceDropdown is the x:Name of picker.
<custom:MyPicker.Behaviors>
<behaviors:EventToCommandBehavior EventName="SelectedIndexChanged"
Command="{Binding Path=BindingContext.DistanceChangedCommand,Source={x:Reference DistanceDropdown}}"></behaviors:EventToCommandBehavior>
</ccustom:MyPicker.Behaviors>
And DistanceChangedCommand has a method
DistanceChangedCommand = new Command<object>(async (x) => await DistanceChangedAction(x as SelectionChangedEventArgs));
The method gets hit, but the args are null
private async Task DistanceChangedAction(SelectionChangedEventArgs selectionChangedEventArgs)
{
await Task.CompletedTask;
}
What am I going wrong? I have also tried with CommandParameter={Binding}
.
Upvotes: 3
Views: 788
Reputation: 9671
The event SelectedIndexChanged
of the Picker View has a delegate handler signature as follow: private void Picker_SelectedIndexChanged(object sender, EventArgs e)
. So your command should cast to EventArgs
and not SelectionChangedEventArgs
.
A better way is to take advantage of CommndParameter
<Picker x:Name="DistanceDropdown" ...>
<Picker.Behaviors>
<xct:EventToCommandBehavior
EventName="SelectedIndexChanged"
Command="{Binding ItemTappedCommand}"
CommandParameter="{Binding Source={x:Reference DistanceDropdown},
Path=SelectedIndex}"/>
</Picker.Behaviors>
and you will expect a parameter of type int
:
DistanceChangedCommand = new Command<int>(async (x) => await DistanceChangedAction(x);
private async Task DistanceChangedAction(int selectedIndex)
{
await Task.CompletedTask;
}
Better yet, you can use AsyncCommand
(also comes with Xamarin-Community-Toolkit):
public ICommand DistanceChangedCommand { get; private set; }
= new AsyncCommand<int>(selectedIndex
=> await Task.CompletedTask);
Upvotes: 3