开发者

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.Conten开发者_StackOverflow中文版t = 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);                  
                  }
           }
       }
    }


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."


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜