Hello,
There are two main issues that need to be addressed to achieve this requirement.
- The specific method of how to bind a button in a ListView to a ViewModel.
- When clicking the button, how to pass the corresponding item in the ListView to the ViewModel.
For problem one, you need to use relative bindings to bind the Command directly to the higher-level ViewModel instead of the ItemSource. You could refer to Bind to an ancestor for more details.
For question two, you need to use CommandParameter
to pass the parameters. Please refer to Using Command parameters for more details.
The following is a minimized example of deleting the corresponding item in a ListView with a button.
<ListView ItemsSource="{Binding Messages}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<HorizontalStackLayout>
<Label Text="{Binding Title}"/>
<Label Text="{Binding Description}"/>
<Button Text="Delete Item" Command="{Binding Source={RelativeSource AncestorType={x:Type c:MyViewModel}}, Path=DeleteCommand}"
CommandParameter="{Binding .}"/>
</HorizontalStackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
ViewModel:
public class Item
{
public string Title { get; set; }
public string Description { get; set; }
}
public class MyViewModel:INotifyPropertyChanged
{
private ObservableCollection<Item> _message = new ObservableCollection<Item>();
public event PropertyChangedEventHandler? PropertyChanged;
public ICommand DeleteCommand { get; private set; }
public ObservableCollection<Item> Messages
{
get
{
return _message;
}
set
{
_message = value;
OnPropertyChanged();
}
}
public void OnPropertyChanged([CallerMemberName] string name = "") =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
public MyViewModel()
{
PopulateData();
}
// implement delete item from list.
private void DeleteDataCommand(object o)
{
var item = o as Item;
if (Messages.Contains(item))
{
Messages.Remove(item);
}
}
void PopulateData()
{
Messages.Add(new Item { Title = "test1", Description = "1st Item" });
Messages.Add(new Item { Title = "test1", Description = "2nd Item" });
DeleteCommand = new Command(x => DeleteDataCommand(x));
}
}
Best Regards,
Alec Liu.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.