user1358072
user1358072

Reputation: 447

listbox double-click to add and remove

I am using WPF and C#. I have a bit trouble with two listboxes. When I double-click an item of ListBox1, it would add the item to ListBox2 and then this item should be removed in ListBox1. Adding is working but removing is not working. I got error message (look at the picture). Any idea why? What may be wrong?

class Shopping
{

    private ObservableCollection<string> _fruits;

    public IEnumerable<string> GetFruits()
    {
        _fruits = new ObservableCollection<string> 
                            {
                                "Apples",
                                "Bananas",
                                "Oranges",
                                "Grapes",
                                "Coconut"
                            };

        return _fruits;
    } 

 public GroceriesList()
    {
        InitializeComponent();

        ListBox1.ItemsSource = _shopping.GetFruits();

    }

    private void ListBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        if (ListBox1.SelectedItem != null)
        {
            ListBox2.Items.Add(ListBox1.SelectedItem);
            ListBox1.Items.Remove(ListBox1.SelectedItem);
        }

    }

enter image description here

Upvotes: 3

Views: 5779

Answers (1)

Gayot Fow
Gayot Fow

Reputation: 8792

They are telling you to add/remove from your variable _fruits PARTIALLY because there is an underlying CollectionViewSource. I would bind the first lb to a list _allFruits and the second lb to a list _selectedFruits. Perform the appropriate add/remove to those lists rather than directly to the lb sources.

It would work something like this (possible compile errors since I cut and paste from your question)...

    private ObservableCollection<string> _fruits;
    private ObservableCollection<string> _fruitsSelected;

    public IEnumerable<string> GetFruits()
    {
        _fruits = new ObservableCollection<string> 
                            {
                                "Apples",
                                "Bananas",
                                "Oranges",
                                "Grapes",
                                "Coconut"
                            };

        return _fruits;
    } 
public GroceriesList()
    {
        InitializeComponent();
        _fruitsSelected = new ObservableCollection<string>();
        ListBox1.ItemsSource = _shopping.GetFruits();
        ListBox2.ItemsSource = _fruitsSelected;

    }

  private void ListBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        if (ListBox1.SelectedItem != null)
        {
            _fruitsSelected.Add(ListBox1.SelectedItem);
            _fruits.Remove(ListBox1.SelectedItem);
        }
    }

This will stop your error from happening and permit the binding to operate in a 'wpf' way. The other difference being that you are using two lists rather than one.

Upvotes: 2

Related Questions