1
votes

This is a part of my program I have a string from sql and a Listbox, I want to select those Items in Listbox that exist in string.

But the problem is this: just last item will be selected by my code!

In addition I use WPF .Net 4.5 and there aren't ListboxItem.selected property and also listBox1.GetItemText!

MYlistbox.SelectionMode=SelectionMode.Multiple;
foreach (var item in MYlistbox.items)
{
 If(Mystring.Contains(item.ToString()))
  {
   MYlistbox.SelectedValue=item.ToString(); 
  }
} 
2
I read previous questions they couldn't help me!user2576835

2 Answers

0
votes
for (int i=0, i< MYlistbox.Items.Count;i++)
{
   if(Mystring.Contains(MYlistbox.Items[i].ToString()))
     {
       MYlistbox.SelectedItems.Add.(MYlistbox.Items[i]);
     }
 }
0
votes

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).