我使用Prism来实现MVVM。如何将ListView.ItemTapped事件绑定到Xamarin Forms中的ViewModel命令?
而我有一个情况,我有一个ListView,并且必须处理ItemTapped事件并且也获取挖掘项目。
我试过使用EventToCommandBehavior。
但我无法让它工作,因为它不能识别已添加的引用。
我使用Prism来实现MVVM。如何将ListView.ItemTapped事件绑定到Xamarin Forms中的ViewModel命令?
而我有一个情况,我有一个ListView,并且必须处理ItemTapped事件并且也获取挖掘项目。
我试过使用EventToCommandBehavior。
但我无法让它工作,因为它不能识别已添加的引用。
EventToCommandBehavior
目前不存在于NuGet上可用的pre1包中。这在pre2发布时应该可用。
我的建议是,你要么EventToCommandBehavior复制到你的项目,现在,或者你可以添加一个,我使用:在XAML中
/// <summary>
/// ListView Item Tapped Behavior.
/// </summary>
public class ItemTappedBehavior : BehaviorBase<ListView>
{
/// <summary>
/// Gets or sets the command.
/// </summary>
/// <value>The command.</value>
public ICommand Command { get; set; }
/// <inheritDoc />
protected override void OnAttachedTo(ListView bindable)
{
base.OnAttachedTo(bindable);
AssociatedObject.ItemTapped += OnItemTapped;
}
/// <inheritDoc />
protected override void OnDetachingFrom(ListView bindable)
{
base.OnDetachingFrom(bindable);
AssociatedObject.ItemTapped -= OnItemTapped;
}
void OnItemTapped(object sender, ItemTappedEventArgs e)
{
if (Command == null || e.Item == null) return;
if (Command.CanExecute(e.Item))
Command.Execute(e.Item);
}
}
然后
<ListView.Behaviors>
<behaviors:ItemTappedBehavior Command="{Binding SelectedItemCommand}" />
</ListView.Behaviors>
我会建议一种不同的方法。
public class AppListView: ListView{
public AppListView(): base(ListViewCachingStrategy.RecycleElement){
this.ItemSelected += (s,e)=>{
this.TapCommand?.Invoke(e.Item);
}
}
#region Property TapCommand
/// <summary>
/// Bindable Property TapCommand
/// </summary>
public static readonly BindableProperty TapCommandProperty = BindableProperty.Create(
nameof(TapCommand),
typeof(System.Windows.Input.ICommand),
typeof(AppListView),
null,
BindingMode.OneWay,
null,
null,
null,
null,
null
);
/// <summary>
/// Property TapCommand
/// </summary>
public System.Windows.Input.ICommand TapCommand
{
get
{
return (System.Windows.Input.ICommand)GetValue(TapCommandProperty);
}
set
{
SetValue(TapCommandProperty, value);
}
}
#endregion
}
现在使用AppListView
代替ListView
和使用TapCommand="{Binding ...}"
。为了使intellisense正常工作,我建议将这个类保存在一个单独的库项目中(一个用于android,一个用于iOS,并将该文件保存在所有库项目之间的共享项目中)。