C# 强制 ListBox 更新元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/519538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# Force ListBox to update elements
提问by mafu
I'm subclassing the standard ListBox control. I get notified of changes to any of the elements added to the list. The task is to update the text shown by the ListBox for the changing element.
我正在继承标准的 ListBox 控件。我会收到有关添加到列表中的任何元素的更改的通知。任务是更新由 ListBox 显示的更改元素的文本。
I'm aware that i could just remove the changed element and add it again, but this seems not preferable for obvious reasons.
我知道我可以删除更改的元素并再次添加它,但由于显而易见的原因,这似乎并不可取。
采纳答案by Marc Gravell
Unfortunately, the data-binding in ListView
doesn't support regular (item) change notification events (FooChanged
/ INotifyPropertyChanged
). However, if you know about the change, you can get the list to re-bind itself. Since you are subclassing, you can call:
不幸的是,数据绑定ListView
不支持常规(项目)更改通知事件(FooChanged
/ INotifyPropertyChanged
)。但是,如果您知道更改,则可以让列表重新绑定自身。由于您是子类化,您可以调用:
this.RefreshItems();
or for a single item:
或对于单个项目:
this.RefreshItem(index);
Otherwise, since this isn't public, you can simulate it by changing the DisplayMember
:
否则,由于这不是公开的,您可以通过更改以下内容来模拟它DisplayMember
:
lb.DisplayMember = "";
lb.DisplayMember = "Bar";
A little hacky, maybe, but it works, and maintains the current selection etc (unlike clearing the DataSource
).
可能有点笨拙,但它可以工作,并保持当前选择等(与清除DataSource
)不同。
回答by Anton Gogolev
Why don't you manually update Text of an item in question? You might also consider rolling out your own databinding mechanism for ListBox. And check out ObjectListViewto see if it's of any help.
为什么不手动更新相关项目的文本?您还可以考虑为 ListBox 推出自己的数据绑定机制。并查看ObjectListView以查看它是否有任何帮助。