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?
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.
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.
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.
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).
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);
}
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.
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