Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在silverlight中删除ListItem_C#_Silverlight - Fatal编程技术网

C# 在silverlight中删除ListItem

C# 在silverlight中删除ListItem,c#,silverlight,C#,Silverlight,我的Silverlight项目中有一个ListBox。当从ListBox中删除和添加ListItem时,我遇到了以下错误 Operation not supported on read-only collection. 代码: 将ItemsControl与ItemsSource一起使用时,不能使用Items集合添加/删除元素。您应该改为修改基础集合 “问题源于我将列表框绑定到一个ObservableCollection,一旦绑定,Items集合将变为只读。”我猜您是通过绑定ItemsSour

我的Silverlight项目中有一个ListBox。当从ListBox中删除和添加ListItem时,我遇到了以下错误

Operation not supported on read-only collection. 
代码:


将ItemsControl与ItemsSource一起使用时,不能使用Items集合添加/删除元素。您应该改为修改基础集合


“问题源于我将列表框绑定到一个ObservableCollection,一旦绑定,Items集合将变为只读。”

我猜您是通过绑定ItemsSource来添加项的吧?如果是这样,请从绑定到的集合中删除该项。

您需要从绑定到
列表框的源中删除该项,而不是从
列表框本身中删除该项。从源代码中删除该项后,
列表框将自动刷新以不显示该项。

如下更改代码:

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);
            }
        }
    }
}

似乎您正在向上移动列表框中选定的项目。

首先,感谢您的关注。此外,我想使用“向上”和“向下”按钮更改项目的位置
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);
            }
        }
    }
}