Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin.Forms ListView set SelectedItem by Code

How can I set the SelectedItem of a ListView in my Code? My problem is, that is isn't highlighted when I preselect an item in my code. The ListView is defined in the xaml file.

<ListView ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}" />

My ViewModel

class MyViewModel
{
    List<MyItem> Items {get; set;}
    MyItem SelectedItem { get; set; }

    public MyViewModel() 
    {
        Items = new List<MyItem>{ ... };
        SelectedItem = Items.First();
    }
}

But when I show the view, it is not highlighting the selected item. When I click on an item, it is highlighted and set correctly. I've played around with property changed, but this shouldn't have an effect, because the property is set right in the constructor.

like image 482
Sven-Michael Stübe Avatar asked Sep 16 '25 15:09

Sven-Michael Stübe


1 Answers

In order for your view to update when properties on MyViewModel change, that class must implement INotifyPropertyChanged. Here's an example:

public class MyViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

But importantly you must call OnPropertyChanged in your setters, so your SelectedItem property will need to look something like this:

MyItem _selectedItem;
MyItem SelectedItem {
  get {
    return _selectedItem;
  }
  set {
    _selectedItem = value;
    OnPropertyChanged("SelectedItem");
  } 
}

Lots of good information on MVVM in Xamarin Forms here: From Data Bindings to MVVM

like image 167
Joel Anair Avatar answered Sep 18 '25 08:09

Joel Anair