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
CodePudding user response:
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.
CodePudding user response:
SelectedItem only works if the object exist in the list, if not, the SelectedIndex property is left at its current value.
Something like this should do the trick:
object tempStarting = startingLbx.SelectedItem;
object tempbench = benchLbx.SelectedItem;
startingLbx.Items.Remove(tempStarting);
benchLbx.Items.Remove(tempbench);
startingLbx.Items.Add(tempbench);
benchLbx.Items.Add(tempStarting);
startingLbx.SelectedItem = tempbench;
benchLbx.SelectedItem = tempStarting;
In the case you want to have the same position in the list
object tempStarting = startingLbx.SelectedItem;
object tempbench = benchLbx.SelectedItem;
int indexStarting = startingLbx.SelectedIndex;
int indexbench = benchLbx.SelectedIndex;
startingLbx.Items.Remove(tempStarting);
benchLbx.Items.Remove(tempbench);
startingLbx.Items.Insert(indexStarting, tempbench);
benchLbx.Items.Insert(indexbench,tempStarting);
startingLbx.SelectedItem = tempbench;
benchLbx.SelectedItem = tempStarting;
I did not test this code but you will get the idea.