Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

Remove selected item from WPF ListBox and ItemSource

$
0
0

I have this working but I'm guessing (hoping?) there's an easier way.

I have a ListBox on a WPF form with Extended Selection mode and the user can remove items from that ListBox. For easy sorting the list items are stored in a List(Of String) called and LstExifEditTags2ListSort and ListBox is filled like this:

Me.LstExifEditTags2.ItemsSource = LstExifEditTags2ListSort

I know I need to manipulate List(Of String) once it becomes the item source and Initially I had this to remove the items:

For Each LstItem In Me.LstExifEditTags2.SelectedItems
      LstExifEditTags2ListSort.Remove(LstItem)
Next
Me.LstExifEditTags2.Items.Refresh()

But that simply deleted the first instance from the list that matched that particular selected item string. So, if the user selected an item near the end of the list that was the same as an item near the start of the list, the first one (near the start of the list) would get deleted and NOT the one the user actually selected.

I couldn't find a way to get index of the selected item in the ListBox so as to match it up with an item in the List(Of String). I ended up looping backward through the selected items, then looping backward through the List(Of String) while the List(Of String).Equals was either equal to the selected item or the counting variable was less than 0. Thusly:

                For i = Me.LstExifEditTags2.SelectedItems.Count - 1 To 0 Step -1
                    LstCount = LstExifEditTags2ListSort.Count - 1
                    While LstCount > -1 And Not LstExifEditTags2ListSort.Item(LstCount).Equals(Me.LstExifEditTags2.SelectedItems(i))
                        LstCount -= 1
                    End While
                    If LstExifEditTags2ListSort.Item(LstCount).Equals(Me.LstExifEditTags2.SelectedItems(i)) Then
                        LstExifEditTags2ListSort.RemoveAt(LstCount)
                    End If
                Next i

So, my question is two fold:

1. Is there an easier way to do this?? (seems like there should be)

2. Does the .Equals simply do a string comparison or is it doing something more like comparing the position of the two things in each list.

Many thanks for any insight that can be offered.

Best,
Ken




Viewing all articles
Browse latest Browse all 18858

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>