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;
}
If you're using MVVM then you can also try another solution:
SelectedValue
to the ViewModel; List
that you bind to the ListBox
set SelectedValue
withvaluesList.FirstOrDefault();
SelectedItem
property of the ListBox
to SelectedValue
(from ViewModel) and set binding Mode="TwoWay"
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With