对不起,标题并没有真正描述这个问题,但这是一个非常奇怪的问题。
为了确保我没有做任何愚蠢的错误,我使用断点来追踪发生的一切......
基本上,我将这段代码放在一个继承自ObservableCollection<T>
:
var n = new MyClass();
int startIndex = 0; // parameter
int length = 2; // parameter
for (int i = 0; i < length; i++)
{
n.Text += this[startIndex].Text;
this.RemoveAt(startIndex);
}
this.Insert(n);
执行代码时,我的收藏有3个项目;循环如下:
n.Text += "some string successfully gotten from this[startIndex]"
this.RemoveAt(startIndex)
n.Text += "some other string successfully gotten from this[startIndex]"
我成功获取该项目,但是当我尝试删除它时出现错误。我迷路了。
非常感谢任何帮助!
提前谢谢。
我试过这个,并得到了相同的结果。
var toRemove = this.Skip(startIndex).Take(length).ToList();
foreach (var b in toRemove)
{
this.Remove(b);
n.Text += b.Text;
}
再次,当Removing
项目时,我有一个 IndexOutOfRange 例外。
在调试时,我的Collection有2个项目,而RemoveAt(0)
仍然会抛出此异常。
我在修改OnCollectionChanged
时尝试手动调用this.Items
。调用OnCollectionChanged
时会触发 IndexOutOfRange 异常,但在从this.Items
删除项目时则不会触发。
for (int i = 0; i < length; i++)
{
this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, Items[startIndex], startIndex));
Items.RemoveAt(startIndex);
}
致电this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset))
后,我也遇到了问题
看起来整个问题来自ListBox。我会尝试使用Bindings和其他东西,并报告。
答案 0 :(得分:0)
this.RemoveAt(startIndex);
,有时候当循环中的可观察集合枚举发生变化时,这是不行的,所以我肯定会把它从循环中删除UPD
我认为你的设计不好我的问题。你说你的类继承了可观察的集合,那么这是什么?尝试更好的设计和定义集合类之外的方法,因为它假装你的集合至少是所有时间的3个元素
UPD 2
设计仍然是丑陋的,但如果你想坚持下去,我在这里做了什么,它的工作原理:
您的收藏定义(不建议您这样做)
public class MyObs : ObservableCollection<MyClass> {
public void Fun() {
var n = new MyClass();
int startIndex = 0; // parameter
int length = 2; // parameter
for (int i = 0; i < length; i++) {
n.Text += this [startIndex].Text;
this.RemoveAt(startIndex);
}
this.Insert(0,n); // PAY ATTENTION THAT I INSERT AT 0 !
}
}
public class MyClass {
public string Text { get; set; }
public override string ToString() {
return Text;
}
}
然后你的XAML:
<ListBox ItemsSource="{Binding MyCollection}"/>
然后你的申报代码:
public MyObs MyCollection { get; set; }
然后初始化和处理:
MyCollection = new MyObs();
MyCollection.Add(new MyClass() {Text = "Item 1"});
MyCollection.Add(new MyClass() { Text = "Item 2" });
MyCollection.Add(new MyClass() { Text = "Item 3" });
MyCollection.Fun();
似乎是您在插入内容中遇到的问题
答案 1 :(得分:0)
我想问题是你在这里引用一个被删除的索引:
var toRemove = this.Skip(startIndex).Take(length).ToList();
foreach (var b in toRemove)
{
this.Remove(b); <<< removed
n.Text += b.Text; <<< referencing the removed
}
这样,显然你有错误描述。从n.text和remove。反转顺序。
答案 2 :(得分:0)
我找到了解决方案。我心疼。
基本上,每次SelectionChanged
更改时都会触发ObservableCollection
,尝试执行某些操作并遇到错误。问题是,Stacktrace中没有任何内容导致这个想法。
很抱歉浪费你的时间(考虑评论/答案的好处),并继续。