Search code examples
c#wpflistlistbox

Wpf Replace Selected List items


enter image description here

I have this Lists here. I want to be able to Select one Object on the left and one on the right, then click the button and it shoudl change them on click.

private void substituteBtn_Click(object sender, RoutedEventArgs e)
{
   object temp = startingLbx.SelectedItem;
   startingLbx.SelectedItem = benchLbx.SelectedItem.ToString();
   benchLbx.SelectedItem = temp.ToString();
}

I have this code to change it. I tried several fixes, but I couldn't find the answer to why my lists are not changing at all after the press of the button. Do I have to change something in the code? Is it because of something in the XAML? I would be happy if someone could help


Solution

  • Here is how you could swap the items directly in the Items collection:

    private void substituteBtn_Click(object sender, RoutedEventArgs e)
    {
        object temp = startingLbx.SelectedItem;
        startingLbx.Items[startingLbx.SelectedIndex] = benchLbx.SelectedItem;
        benchLbx.Items[benchLbx.SelectedIndex] = temp;
    }
    

    If you're using the ItemsSource property, you should swap the items in the source collections.