首页 > 解决方案 > 带有命令参数的点击手势

问题描述

我有一个列表视图,其 ItemTemplate 定义如下:

<ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout>
                            <Grid>
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="Auto"/>
                                </Grid.RowDefinitions>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="0.7*" />
                                    <ColumnDefinition Width="0.3*" />
                                </Grid.ColumnDefinitions>
                                <Label Text="{Binding AddressTypeName}" Grid.Column="0"/>
                                <Label Text="&#xE74D;"
                                       Grid.Column="1"
                                       FontFamily="{StaticResource SegoeMDL2Assets}" FontSize="Medium" HorizontalOptions="End">
                                    <Label.GestureRecognizers>
                                        <TapGestureRecognizer Tapped="OnDelete_Tapped" CommandParameter="{Binding .}"/>
                                    </Label.GestureRecognizers>
                                </Label>

                            </Grid>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>

            </ListView.ItemTemplate>

我的文件后面的代码处理 OnDelete_Tapped 如下:

      public void OnDelete_Tapped(object sender, EventArgs e)
    {
        viewModel.DeleteCommand.Execute(e);

        viewModel.LoadAddressTypesCommand.Execute(true);
    }

EventArgs e 确实返回了一个 EventArgs 对象,其中包含正确的对象(在我的例子中,是正确的 AddressType 对象)。

ViewModel 定义了这个:

       public ICommand DeleteCommand => new Command<AddressType>(DeleteCommandExecute);

    void DeleteCommandExecute(AddressType address)
    {
        if (IsBusy)
            return;
        IsBusy = true;

        try
        {
            DataStore.DeleteAddressTypeAsync(address.Id);
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
        }
        finally
        {
            IsBusy = false;
        }
    }

DeleteCommand 永远不会执行。我可以单步执行代码,但它永远不会在我的 viewModel 中调用 DeleteCommand。LoadAddressTypesCommand 运行正常 - 不仅来自后面的代码,而且在其他地方我将该命令绑定为我的 viewModel 的命令。任何想法我做错了什么?提前致谢。

标签: formsxamarincommandparameter

解决方案


你可以试试这个:

在xml中:

<TapGestureRecognizer Tapped="OnDelete_Tapped" CommandParameter="{Binding .}"/>

那么 e.Parameter 将是您在 CommandParameter 中设置的任何内容。

public void OnDelete_Tapped(object sender, TappedEventArgs e)
{
    var addressType = (e.Parameter) as AddressType;
    viewModel.DeleteCommand.Execute(addressType );
    viewModel.LoadAddressTypesCommand.Execute(true);
}

或者直接使用 ICommand

<TapGestureRecognizer
        Command="{Binding DeleteCommand}"
        CommandParameter="{Binding .}" />

推荐阅读