Xamarin.Forms ListView set SelectedItem by Code

强颜欢笑 提交于 2019-12-11 11:13:40

问题


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.


回答1:


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




回答2:


In my case was simply this.... (for example select automatically the first element with one element)

 protected override async void OnAppearing()
{
    if (MyList.Count == 1)
                {
                    List_CheckPoint.SelectedItem = MyList[0];
                }
    }


来源:https://stackoverflow.com/questions/32870279/xamarin-forms-listview-set-selecteditem-by-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!