views:

2156

answers:

5

In WPF, I'd like to set the selected indexes of a System.Windows.Controls.ListBox

I best way I've found so far is to remove all the items from the control, insert the selected, call SelectAll(), then insert the rest, but this solution neither works in my situation nor is very efficient.

So, how do you set items in a Listbox to be selected, programmatically?

+1  A: 

One way you can do this is to add a Selected field to your data object. Then you need to overide the default listboxitem style and bind the isselected property to the Selected property in your object. Then you just need to go through your data items and update the Selected value.

If you don't implement that Selected property as a dependency property, you need your class to implented the INotifyPropertyChanged interface and raise the propertychanged event when you set the value.

mdm20
This worked perfectly, thank you very much!
Alex
+1  A: 

You have to do this:

ListBoxObject.SelectedItem = itemIndex;

Where itemIndex would be the item you want to select. If you want to select multiple items, you need to use the ListBox.SelectedIndexCollection property.

Jon
System.Windows.Controls.ListBox is not like System.Windows.Forms.ListBox in contining a SelectedIndexCollection property
Alex
My bad. Sorry about that.
Jon
SelectedItem will still work.
Bryan Anderson
+1  A: 

You can set multiple items as selected by using the SelectedItems collection. This isn't by index, but by what you have bound:

foreach (var boundObject in objectsBoundToListBox)
{
    ListBox.SelectedItems.Add(boundObject);
}
danlash
A: 

bravooooooo!!! it works

A: 

how to programmatically select multiple items in listbox in wpf

foreach (var boundObject in objectsBoundToListBox) { ListBox.SelectedItems.Add(boundObject); }