Hello,
You need to use data binding to make ListView aware of the SelectedItem
change and trigger the ItemSelected
event by emitting a broadcast via the OnPropertyChanged
method.
Please refer to the following steps:
Step 1. Implement the INotifyPropertyChanged interface in ViewModel:
MainViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string name = "") =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
Step 2. Implement the property for binding to SelectedItem:
private Item selItem;
public Item SelItem
{
get
{
return selItem;
}
set
{
if (value != selItem)
{
selItem = value;
OnPropertyChanged(); // reports this property has changed.
}
}
}
Step 3. Set SelItem in ViewModel, such as SelItem = Items[1]; // Items is binding to ItemsSource of ListView
.
Step 4. Binding the ViewModel to ListView:
// in the page code behind
BindingContext = new MainViewModel();
// in xaml
<ListView ItemSelected="vegColl_ItemSelected" ItemsSource="{Binding Items}" SelectedItem="{Binding SelItem,Mode=TwoWay}">
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.