MaxCoder88
MaxCoder88

Reputation: 2428

Remove ListItem in silverlight

I have a ListBox in my Silverlight project.And,when to remove and add ListItem from a ListBox,I got the following error.

Operation not supported on read-only collection. 

Code:

public void btnUp_Click(object sender, RoutedEventArgs e)
    {
      if (lbChoices.SelectedItem != null)
        {
           ListBoxItem selectedItem = new ListBoxItem();          
           selectedItem.Content = lbChoices.SelectedItem;
           selectedItem.IsSelected = true;
           int selectedIndex = lbChoices.SelectedIndex;
           if (lbChoices.Items.Count > 1)
           {              
              if (selectedIndex > 0)
                {
                    lbChoices.Items.Remove(lbChoices.SelectedItem);       
                    lbChoices.Items.Insert(selectedIndex - 1, selectedItem);                  
                  }
           }
       }
    }

Upvotes: 1

Views: 1354

Answers (4)

Ebrahim Asadi
Ebrahim Asadi

Reputation: 384

Change your code like this:

private void button1_Click(object sender, RoutedEventArgs e)
{
    if (lbChoices.SelectedItem != null)
    {
        ListBoxItem selectedItem = (ListBoxItem)lbChoices.SelectedItem; 
        int selectedIndex = lbChoices.SelectedIndex;
        if (lbChoices.Items.Count > 1)
        {
            if (selectedIndex > 0)
            {
                lbChoices.Items.Remove(lbChoices.SelectedItem);
                lbChoices.Items.Insert(selectedIndex - 1, selectedItem);
            }
        }
    }
}

It seems that your are moving up the selected item in the list box.

Upvotes: 0

Kelsey
Kelsey

Reputation: 47736

You need to remove the item from the source that your ListBox is bound to not the ListBox itself. As soon as your remove it from the source, the ListBox will automatically refresh to not display the item.

Upvotes: 1

Emond
Emond

Reputation: 50682

I guess you added items by binding the ItemsSource? If so, remove the item from the collection you are binding to.

Upvotes: 1

Jethro
Jethro

Reputation: 5916

When you are using ItemsControl with an ItemsSource, you can not add/remove elements using the Items collection. You should modify your underlying collection instead.

"The problem stems from the fact that I’d bound my ListBox to an ObservableCollection, once bound the Items collection becomes read-only."

Upvotes: 1

Related Questions