c# - 使用 EventToCommandBahavior 的 Xamarin 表单选择器

标签 c# xamarin.forms mvvm picker xamarin-community-toolkit

我有一个自定义选择器。我需要在选择器的选择更改时调用 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/

相关文章:

c# - WPF MVVM 动态地将带有两个控件的行添加到 Grid/DataGrid

c# - 了解 Google V8 的架构

c# - Xamarin.Forms:应用程序关闭时广播接收器不工作

c# - 检索在 Func 中执行的调用方法的名称

c# - Xamarin.Forms 中的 IOS 联系人邮政地址

c# - 自动调整 WebView 大小以适合内容

wpf - 如何或何时清理 WPF/MVVM 中的 RelayCommand 对象?

c# - INotifyPropertyChanged 绑定(bind)未按预期更新

c# - DataGrid 动态表由空白行填充 C#

java - C# 的 getBytes ("UTF-8") 和 Encoding.UTF8.GetBytes() 之间的区别