Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically selecting Items/Indexes in a ListBox

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?

like image 692
Alex Avatar asked May 06 '09 19:05

Alex


People also ask

How to get selected item index in ListBox in c#?

To retrieve a collection containing the indexes of all selected items in a multiple-selection ListBox, use the SelectedIndices property. If you want to obtain the item that is currently selected in the ListBox, use the SelectedItem property.

How do I select an item in ListBox?

To select an item in a ListBox, we can use the SetSelect method that takes an item index and a true or false value where the true value represents the item to be selected. The following code snippet sets a ListBox to allow multiple selection and selects the second and third items in the list: listBox1.

How to select item in ListBox wpf?

GetItemAt(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.

How do I know if an item is selected in ListBox?

To determine the items that are selected, you can use the Selected property of the list box. The Selected property of a list box is an array of values where each value is either True (if the item is selected) or False (if the item is not selected).


Video Answer


2 Answers

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);
}
like image 176
danlash Avatar answered Oct 05 '22 13:10

danlash


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.

like image 41
mdm20 Avatar answered Oct 05 '22 11:10

mdm20