Chuanyu Wang
Chuanyu Wang

Reputation: 47

How to select one item in ListBox

In the WPF ListBox control, I am trying to update the ListBox.DataContext and select the last one item. But it fails.

public void Update_Button_Click()
{
    this.MyListBox.BeginInit();
    this.MyListBox.DataContext = family; // family is a collection of Person object.
    this.MyListBox.EndInit();
    this.MyListBox.SelectedIndex = family.Count - 1;
}

But no item is selected in ListBox

<ListBox Name="MyListBox" ItemsSource="{Binding}"/>

I tried to update the SelectedIndex in handler of SourceUpdated event, it also fails.

Upvotes: 1

Views: 583

Answers (1)

ASanch
ASanch

Reputation: 10383

I tried your example and it works fine. Is there anything else in your code that may affect this?

Upvotes: 1

Related Questions