forms - 带有命令参数的点击手势
问题描述
我有一个列表视图,其 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=""
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 的命令。任何想法我做错了什么?提前致谢。
解决方案
你可以试试这个:
在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 .}" />
推荐阅读
- frida - 如何在android中打印调用的函数?
- mysql - 更改 spring jpa 现有表列类型
- c++ - 如何从平面缓冲区中反序列化联合结构的 void* 值的大小
- python-3.x - 我应该如何从 Python 中的字符串自动创建变量?
- r - 我想创建一个按订单 ID 分组的最大日期列
- sql - 访问查询:无法获得正确的计数
- kernel - 如何使用 seccomp_release libseccomp?
- swift - “协议”类型的值没有成员“功能”
- node.js - 将图像上传到您的网站 Node js 的正确方法是什么
- android - 如何检测该应用程序是否在测试版 Android 上运行?