Selecting the first item in a list

The list works as autocomplete in richtextbox. I fill it with elements from the collection. I need it to automatically select the first item every time a list is populated.

How to do it?

thanks

foreach (var ks in ksd.FindValues(comparable)) { lb.Items.Add(ks.Value); } if (lb.HasItems) { lb.Visibility = System.Windows.Visibility.Visible; lb.SelectedIndex = 0; //Suggested solution, still doesn't work } else { lb.Visibility = System.Windows.Visibility.Collapsed; } 
+7
source share
4 answers

You can put SelectedIndex at 0 in XAML for the first time at boot

 <ListBox SelectedIndex="0" /> 

In code mode, you can do this after loading a list of items

  if (this.lst.Items.Count > 0) this.lst.SelectedIndex = 0; 
+24
source

If you are using MVVM, you can also try another solution:

  • Add a property called SelectedValue in ViewModel;
  • After loading (or adding) the values ​​to the List , which you bind to the ListBox set SelectedValue with valuesList.FirstOrDefault();
  • On XAML, bind the SelectedItem property from ListBox to SelectedValue (from ViewModel) and set the binding Mode="TwoWay"
+9
source

This should work:

 listBox1.SetSelected(0,true); 
+2
source

You do not need anything, only the data that you use. You should not be wondering what the control looks like. (You do not want to be combined with this control)

 <ListBox ItemsSource="{Binding MyItems}" SelectedItem="{Binding MyItem}" /> 

may be:

 <SexyWoman Legs="{Binding MyItems}" Ass="{Binding MyItem}" /> 

and it will also work.

ListBox has this class as a DataContext:

 class DummyClass : INotifyPropertyChanged { private MyItem _myItem; public MyItem MyItem { get { return _myItem; } set { _myItem = value; NotifyPropertyChanged("MyItem"); } } private IEnumerable<MyItem> _myItems; public IEnumerable<MyItem> MyItems { get { return _myItems; } } public void FillWithItems() { /* Some logic */ _myItems = ... NotifyPropertyChanged("MyItems"); /* This automatically selects the first element */ MyItem = _myItems.FirstOrDefault(); } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(string value) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(value)); } } #endregion } 
0
source

All Articles