C# 在silverlight中删除ListItem
我的Silverlight项目中有一个ListBox。当从ListBox中删除和添加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
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);
}
}
}
}