I am trying to bind an event to a ListView, on my menu page, using the itemtapped property. Currently I am using MVVM (Xamarin form labs) framework in my app. What I am trying t
Alternatively you can use an Attached Behavior
public static class ListViewAttachedBehavior
{
public static readonly BindableProperty CommandProperty =
BindableProperty.CreateAttached (
"Command",
typeof(ICommand),
typeof(ListViewAttachedBehavior),
null,
propertyChanged:OnCommandChanged);
static void OnCommandChanged (BindableObject view, object oldValue, object newValue)
{
var entry = view as ListView;
if (entry == null)
return;
entry.ItemTapped += (sender, e) =>
{
var command = (newValue as ICommand);
if(command == null)
return;
if(command.CanExecute(e.Item))
{
command.Execute(e.Item);
}
};
}
}
Then call it on your ListView
<ListView
RowHeight="70"
x:Name="AcquaintanceListView"
b:ListViewAttachedBehavior.Command="{Binding ItemSelectedCommand}"
ItemsSource="{Binding Acquaintances}">
I've followed the same architecture and done through creating custom list control and created 1 bindable property with command which I've override in my View Model using below code:
Custom Control [.cs] page in my PCL
using System;
using System.Windows.Input;
using Xamarin.Forms;
namespace YourNS {
public class ListView : Xamarin.Forms.ListView {
public static BindableProperty ItemClickCommandProperty = BindableProperty.Create<ListView, ICommand>(x => x.ItemClickCommand, null);
public ListView() {
this.ItemTapped += this.OnItemTapped;
}
public ICommand ItemClickCommand {
get { return (ICommand)this.GetValue(ItemClickCommandProperty); }
set { this.SetValue(ItemClickCommandProperty, value); }
}
private void OnItemTapped(object sender, ItemTappedEventArgs e) {
if (e.Item != null && this.ItemClickCommand != null && this.ItemClickCommand.CanExecute(e)) {
this.ItemClickCommand.Execute(e.Item);
this.SelectedItem = null;
}
}
}
}
My XAML Page
<ContentPage ...
xmlns:local="clr-namespace:Samples.Views;assembly=Your Assebly Name">
<local:ListView ItemClickCommand="{Binding Select}"
ItemsSource="{Binding List}">
And in my View Model [In this example, I've only opened dialog action sheet
private Command<Signature> selectCmd;
public Command<Signature> Select {
get {
this.selectCmd = this.selectCmd ?? new Command<Signature>(s =>
this.dialogs.ActionSheet(new ActionSheetConfig()
.Add("View", () => {
if (!this.fileViewer.Open(s.FilePath))
this.dialogs.Alert(String.Format("Could not open file {0}", s.FileName));
})
.Add("Cancel")
)
);
return this.selectCmd;
}
}