The item in Items
collection is item data, not ListBoxItem
, you should use ItemContainerGenerator
to obtain the container which is ListBoxItem and use IsSelected
property:
foreach (var item in MYlistbox.items){
if(Mystring.Contains(item.ToString())) {
var lbItem = MYlistbox.ItemContainerGenerator.ContainerFromItem(item) as ListBoxItem;
if(lbItem != null){
lbItem.IsSelected = true;
}
}
}
Also note that ItemContainerGenerator
works only if the item is loaded and rendered. It's a pity that ListBox also uses a VirtualizingStackPanel
by default. So the code snippet works only for visible items (hidden items won't have any container rendered). If your listbox does not contains a large collection, virtualizing may not be needed, you can then disable virtualizing like this:
VirtualizingStackPanel.SetIsVirtualizing(MYlistbox, false);
MYlistbox.UpdateLayout();//this is very important
If keeping using virtualizing, I think you have to somehow bind IsSelected
to your viewModel using a binding with some converter. This approach is more complicated but more friendly with MVVM (and should be done if you're familiar with mvvm).