ListView SelectedItem can't set in code

Fei Xu 490 Reputation points
2023-05-02T07:25:56.5266667+00:00

ListView can't set selecteditem in code, if set it in code,it does not display in view and have not ItemSelected event.

Developer technologies | .NET | .NET MAUI
0 comments No comments
{count} votes

Accepted answer
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 50,126 Reputation points Microsoft External Staff
    2023-05-02T08:44:52.3666667+00:00

    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.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.