Binding to ListView item tapped property from View Model

后端 未结 2 681
北荒
北荒 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:33

    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

     
    

提交回复
热议问题