问题描述
我遇到这样的异常:
我在viewModel中有一个属性:
I have a property in viewModel:
private ObservableCollection<TreeViewItem> fooStorage=new ObservableCollection<TreeViewItem>();
public ObservableCollection<TreeViewItem> FooStorage
{
get { return facetStorage; }
set { facetStorage = value; }
}
但是,在我清除FooStorage
并尝试添加新项目之后:
However, after I cleared FooStorage
and trying to add new item:
private void LoadData()
{
if (FooStorage.Count > 0)
{
FooStorage.Clear();
}
for (int k = 0; k < lengthOfColl; k++)
{
FooStorage.Add(new TreeViewItem() { Header=k.ToString()});//here is exception
}
}
我有一个例外.
当我第一次调用LoadData()方法时,一切正常.然后,如果我第二次调用方法LoadData(),则会收到此类异常.
When I call a method LoadData() at the first time, it all works okay. Then if I call a method LoadData() at the second time, then I get a such exception.
有人遇到过这样的例外吗?我无法在测试项目中重现此异常的最有趣的事情.
Have anybody met a such exception? The most interesting thing that I cannot reproduce this exception in a test project.
StackTrace:
StackTrace:
更新:
我正在从FooStorage
向位于DataGridTextBoxColumn
的HeaderTemplate内的其他TreeView
添加新的TreeViewItem's
.因此,当用户单击DataGridTextBoxColumn2
的Header1
时,Header1
的TreeView
将由viewModel中的FooStorage
填充.好的.当用户单击DataGridTextBoxColumn2
的Header2
时,应从viewModel中的FooStorage
填充Header2
的TreeView
,但是当我Clear()
和Add()
新项添加到FooStorage
时,则我上面有一个例外.
I am adding new TreeViewItem's
from FooStorage
to different TreeView
placed inside of HeaderTemplate of DataGridTextBoxColumn
. So when user clicks at Header1
of DataGridTextBoxColumn2
, then TreeView
of Header1
is populated by FooStorage
from viewModel. OK. The when user clicks at Header2
of DataGridTextBoxColumn2
, then TreeView
of Header2
should be populated by FooStorage
from viewModel, however when I Clear()
and Add()
new items to FooStorage
, then I've got an above exception.
推荐答案
只想说将UI元素TreeViewItem
传递给ViewModel
是一种不好的做法.所以也许添加新的TreeViewItem
然后在不同的地方使用是我的问题.
Just would like to say that passing UI Element TreeViewItem
to ViewModel
is a bad practice. So maybe adding new TreeViewItem
which is then used in different places was my problem.
正如@Sinatr所说:
As @Sinatr said:
帕特里克·霍夫曼(Patrick Hofman)给了我建议,以在用户界面中禁用该部分,然后在禁用它之后,就没有问题了.
Patrick Hofman gave me advice to disable that section in the UI and after I disabled it, then there was no problems.
因此,我得出的结论是,我已经遭受了不良习惯的后果,并受到了惩罚. 避免不良做法.而ObservableCollection<T>
则无罪!抱歉,ObservableCollection<T>
.
So I've concluded that I've met consequences of using bad practice and was punished. Avoid bad practices. And ObservableCollection<T>
is not guilty! Sorry, ObservableCollection<T>
.
现在我正在学习TreeView由乔什·史密斯(Josh Smith).
这篇关于“指定的参数超出有效值范围.参数名称:索引"当将新项目添加到ObservableCollection< T>时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!