我注意到PropertyGrid与BindingList结合的奇怪行为。
将项目添加到BindingList时,PropertyGrid首先清除BindingList中的所有项目,然后再逐一添加所有以前的项目,然后才将新项目添加到其中。
我的问题是,它引发了' ListChanged'事件每次,但我只是想为每个添加的项目提供一次,而不是例如在添加第二项时为3次。
以下是一个例子:
private void Form1_Load(object sender, EventArgs e)
{
propertyGrid1.SelectedObject = new Foo();
}
private class Foo
{
[DisplayName("BindingList")]
[Description("BindingList")]
[Category("BindingList")]
[Browsable(true)]
public BindingList<int> Bar { get; set; } = new BindingList<int>();
public int BindingListEventRaiseCount { get; set; } = 0;
public Foo(){
Bar.ListChanged += OnBinListChanged;
}
private void OnBinListChanged(object sender, EventArgs e){
BindingListEventRaiseCount++;
Console.WriteLine("Current ListElementsCount: " + ((BindingList<int>)sender).Count);
}
}
通过propertyGrid控件添加3个项目时输出:
Current ListElementsCount: 0
Current ListElementsCount: 1
Current ListElementsCount: 0
Current ListElementsCount: 1
Current ListElementsCount: 2
Current ListElementsCount: 0
Current ListElementsCount: 1
Current ListElementsCount: 2
Current ListElementsCount: 3
是否有针对此错误的修复程序?
答案 0 :(得分:1)
我不知道这是否有帮助,但在再次创建项目之前始终有Reset
按下确定时,也会执行重置。
private void OnBinListChanged(object sender, ListChangedEventArgs e)
{
switch (e.ListChangedType)
{
case ListChangedType.ItemAdded:
BindingListEventRaiseCount++;
Console.WriteLine("Current ListElementsCount: " + ((BindingList<int>)sender).Count);
break;
case ListChangedType.Reset:
Console.WriteLine("Reset");
break;
}
}
输出(4项):
Reset
Current ListElementsCount: 1
Reset
Current ListElementsCount: 1
Current ListElementsCount: 2
Reset
Current ListElementsCount: 1
Current ListElementsCount: 2
Current ListElementsCount: 3
Reset
Current ListElementsCount: 1
Current ListElementsCount: 2
Current ListElementsCount: 3
Current ListElementsCount: 4
Reset
Current ListElementsCount: 1
Current ListElementsCount: 2
Current ListElementsCount: 3
Current ListElementsCount: 4