PuZZled
PuZZled

Reputation: 23

How to select an item in a listbox programatically using its index using c#

I have a listbox which can be edited. Once an item in that listbox is edited and saved, the newly edited item is displayed in the list however its position changes. I want to be able to have that item selected or highlighted even afer its position changes. I can get its new index however I couldnt manage to find a way to have re-selected programitcally after its psoiton changes in the listbox!

Any help here would be greatly appreciated Thanks

Upvotes: 1

Views: 7892

Answers (2)

blindmeis
blindmeis

Reputation: 22445

i assume that the itemssource is some kind of collection. why you dont use the SelectedItem property with Mode=TwoWay to select the item you want from your c# code?

<ListBox ItemsSource="{Binding Path=YourItemsCollection}"
         SelectedItem="{Binding Path=MySelectedItem, Mode=TwoWay}" />

another way is to use the ICollectionView MoveCurrentTo method. all you have to do is to create a ICollectionView with CollectionViewSource.GetDefaultView(this.YourItemsCollection). if you take this way you do not need binding to SelectedItem but you have to set IsSynchronizedWithCurrentItem=true for your listbox.

Upvotes: 0

Vladimir
Vladimir

Reputation: 3689

ListBox.SelectedIndex = newPosition;

or

ListBox.SelectedIndices.Add(newPosition);

with an optional SelectedIndices.Clear() before if you want just your item to be selected.

Upvotes: 2

Related Questions