7/13/10

WPF listbox.SelectedItems.Add doesn't select the items?

D'oh, I guess it's binding or ref 101, make sure you iterate through correct items list, which in this case - the bound items.

lets pretend to bind the listBox to some list of states:

listBox.ItemSource = somelistOfStates;

at some point you need to select some states programmatically that come from some other list of states (you get it from some event, for example):
foreach(var state in _statesIWantToSelect)
     listBox.SelectedItems.Add (state);

Looks right, but doesn't work (does not select the states in the listBox).
Well, the reason why is that SeletedItems list does not find the state you want it to select in its list.You have to find the corresponding listbox item first then operate on that item not on some other object that doesn't have the same reference:
 
foreach(var state in _statesIWantToSelect)
    foreach(var item in listBox.Items)
        if(((State)item == state)
            listBox.SelectedItems.Add(item)

   



No comments:

Post a Comment