我有一个 XF 应用程序,其中定义了以下 Collection View 。第二个标签有一个 TapGestureRecognizer,当我点击标签(在 Android 上尝试这个)时,它不会在模型中触发 DoSomethingInteresting
。请问有人能看出是什么问题吗?
工作样本可以是 cloned from here .
XAML
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:SampleApp"
x:Class="SampleApp.MainPage">
<StackLayout>
<CollectionView ItemsSource="{Binding GaugeSites}">
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="40" />
</Grid.RowDefinitions>
<Label Grid.Column="0"
Text="{Binding Description}"
FontSize="20"
Margin="10"
TextColor="Black"
FontAttributes="Bold" />
<Label Grid.Column="1"
Margin="10"
FontSize="20"
Text="Click Me!">
<Label.GestureRecognizers>
<TapGestureRecognizer Command="{Binding DoSomethingInteresting}" />
</Label.GestureRecognizers>
</Label>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</StackLayout>
</ContentPage>
型号
namespace SampleApp
{
public class MainPageModel : FreshBasePageModel
{
public MainPageModel() : base()
{
GaugeSites = new List<GaugeSite>();
for (var index = 1; index <= 5; index++)
{
GaugeSites.Add(new GaugeSite()
{
Description = $"Gauge Site {index}"
});
}
}
public List<GaugeSite> GaugeSites { get; set; }
public Command DoSomethingInteresting
{
get
{
return new Command(() =>
{
});
}
}
}
[AddINotifyPropertyChangedInterface]
public class GaugeSite
{
public string Description { get; set; }
}
}
最佳答案
也许这是多余的,但我会捕获机会。正如其他答案所示,您需要将 TapGestureRecognizer 中的源设置为 CollectionView 的名称。但是,了解哪个 GaugeSite 实例与其 TabGestureRecognizer 被点击的 CollectionView 项相关联可能很有用。要添加此信息,请添加一个 CommandParamter,即
<Label.GestureRecognizers>
<TapGestureRecognizer Command="{Binding BindingContext.DoSomethingInteresting,
CommandParameter="{Binding}"
Source={x:Reference YourCollectionName}}" />
</Label.GestureRecognizers>
说到你可以使用的命令
DoSomethingInteresting = new Command<GaugeSite>((a) => DoSomething(a));
在您的 View 模型构造函数中。 lambda 引用的方法是
void DoSomething(GaugeSite gaugeSite)
{
// ....
}
希望对你有帮助
关于Xamarin Forms CollectionView TapGestureRecognizer 未在标签上触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57914705/