Listview SelectedItem in MVVM

Create Helper class named ListViewBehaviours
-------------------------------

ListViewBehaviours.cs

 public class ListViewBehaviours : Behavior<ListView>
{

public static readonly BindableProperty CommandProperty = BindableProperty.Create(
propertyName: "Command",
returnType: typeof(ICommand),
declaringType: typeof
(ListViewBehaviours));

public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}



protected override void OnAttachedTo(ListView bindable)
{
base.OnAttachedTo(bindable);
bindable.ItemSelected += Bindable_ItemSelected;
bindable.BindingContextChanged += Bindable_BindingContextChanged;

}

private void Bindable_BindingContextChanged(object sender, EventArgs e)
{
var lv = sender as ListView;
BindingContext = lv?.BindingContext;

}

private void Bindable_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{


if (e.SelectedItem == null) {
                return; // ensures we ignore this handler when the selection is just being cleared
            }
 
Command.Execute(null);

((ListView)sender).SelectedItem = null; 
 


}

protected override void OnDetachingFrom(ListView bindable)
{
base.OnDetachingFrom(bindable);
bindable.ItemSelected -= Bindable_ItemSelected;
bindable.BindingContextChanged -= Bindable_BindingContextChanged;
        }
    }

-------------------------------

XAML

Add namespace 

  xmlns:localcontrol="clr-namespace:Projectname"


End of Item template of Listview Add below lines       

 <ListView  SelectedItem="{Binding SelectedItem}"  >

.............................
</DataTemplate>
                </ListView.ItemTemplate>
                <ListView.Behaviors>
                    <localcontrol:ListViewBehaviours Command="{Binding SelectedCommand}" />
                </ListView.Behaviors>
</ListView>

---------------------------------------

ViewModel
  #region SelectedCommand
        public ICommand SelectedCommand => new Command(async () =>
        {
            if (isClicked)
            {
                 /// Provide your stuff here
                       await navi.pushasync(new Page(SelectedItem.ID))
            }
            await Task.Run(async () =>
            {
                await Task.Delay(500);
                isClicked = true;
            });
        });

        private ModelName_SelectedItem;
        public ModelName SelectedItem
        {
            get { return _SelectedItem; }
            set { _SelectedItem = value; OnPropertyChanged(); }
        }
        #endregion



Comments

Popular posts from this blog

Button click event with current object from listview having button

SideMenu React native