Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting first item in listbox

Tags:

c#

wpf

listbox

A listbox works as an auto-complete within a richtextbox I am populating it with items from a collection. I need it to auto select first item every time listbox populates.

How do I do this?

Thank you

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;
      }
like image 721
gumenimeda Avatar asked Nov 22 '11 03:11

gumenimeda


2 Answers

If you're using MVVM then you can also try another solution:

  1. Add property called SelectedValue to the ViewModel;
  2. After loading (or adding) values to the List that you bind to the ListBox set SelectedValue withvaluesList.FirstOrDefault();
  3. On the XAML bind the SelectedItem property of the ListBox to SelectedValue (from ViewModel) and set binding Mode="TwoWay"
like image 178
Anatolii Gabuza Avatar answered Sep 18 '22 12:09

Anatolii Gabuza


You can put SelectedIndex to 0 in XAML for the first time loading

<ListBox SelectedIndex="0" />

In code-behind, you can do this after loading items list

        if (this.lst.Items.Count > 0)
            this.lst.SelectedIndex = 0;
like image 29
Peter PAD Avatar answered Sep 17 '22 12:09

Peter PAD