你不应该添加TapGestureRecognizer
to a ListView
。每个单元格都已经有处理点击它们的事件,而 GestureRecognizer 可能只会混淆ListView
关于水龙头应该做什么。有几种方法可以解决这个问题。
1.SelectedItem绑定
Bind a SelectedItem
财产给ListView
并在该属性的设置器中处理您的方法调用。
<ListView x:Name="dataList" ItemsSource="{Binding routeLabels}"
HasUnevenRows="True" Grid.Row="1" Grid.Column="0"
Grid.ColumnSpan="3" SelectedItem="{Binding SelectedItem}">
</ListView>
在你的视图模型中:
string _selectedItem;
public string SelectedItem {
get {return _selectedItem; }
set
{
_selectedItem = value;
// Additional code
}
}
2. 使用内置事件 ItemSelected 或 ItemTapped
A ListView
有一些您可以连接的事件ItemSelected
and ItemTapped
。这些可以被隐藏在代码隐藏中,并且可以处理您想要实现的目标。
<ListView x:Name="dataList" ItemsSource="{Binding routeLabels}"
HasUnevenRows="True" Grid.Row="1" Grid.Column="0"
Grid.ColumnSpan="3" ItemSelected="Handle_ItemSelected" ItemTapped="Handle_ItemTapped">
</ListView>
3.使用事件来命令与行为绑定
由于您使用视图模型,所以理想情况下您不需要这些事件,因为它们是在 UI 端处理的。有一些 NuGet 包可以将事件转换为可以在视图模型中处理的命令。看一眼科卡夫行为 https://github.com/corradocavalli/Corcav.Behaviors例如。
4. 创造自己的行为
我有一个经常使用的东西,看起来像这样:
public class ListViewSelectedItemBehavior : Behavior<ListView>
{
public static readonly BindableProperty CommandProperty = BindableProperty.Create(nameof(Command), typeof(ICommand), typeof(ListViewSelectedItemBehavior));
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
public ListView AssociatedObject { get; private set; }
protected override void OnAttachedTo(ListView bindable)
{
base.OnAttachedTo(bindable);
AssociatedObject = bindable;
bindable.BindingContextChanged += OnBindingContextChanged;
bindable.ItemSelected += OnListViewItemSelected;
}
protected override void OnDetachingFrom(ListView bindable)
{
base.OnDetachingFrom(bindable);
bindable.BindingContextChanged -= OnBindingContextChanged;
bindable.ItemSelected -= OnListViewItemSelected;
AssociatedObject = null;
}
private void OnBindingContextChanged(object sender, EventArgs e)
{
OnBindingContextChanged();
}
private void OnListViewItemSelected(object sender, SelectedItemChangedEventArgs e)
{
if (Command == null)
return;
if (Command.CanExecute(e.SelectedItem))
Command.Execute(e.SelectedItem);
}
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
BindingContext = AssociatedObject.BindingContext;
}
}
要将其添加到您的ListView
您只需向其添加一个行为:
<ListView x:Name="dataList" ItemsSource="{Binding routeLabels}"
HasUnevenRows="True" Grid.Row="1" Grid.Column="0"
Grid.ColumnSpan="3">
<ListView.Behaviors>
<behaviors:ListViewSelectedItemBehavior Command="{Binding ItemSelectedCommand}" />
</ListView.Behaviors>
</ListView>
在这种情况下ItemSelectedCommand
是 ViewModel 中的 Command 对象。