Binding to ListView item tapped property from View Model

后端 未结 2 679
北荒
北荒 2021-02-02 14:38

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

2条回答
  •  清酒与你
    2021-02-02 15:37

    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(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

    
    
    
    

    And in my View Model [In this example, I've only opened dialog action sheet

    private Command selectCmd;
            public Command Select {
                get {
                    this.selectCmd = this.selectCmd ?? new Command(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;
                }
            }
    

提交回复
热议问题