C# 如何更新 ObservableCollection 的现有元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/800091/
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
How do I update an existing element of an ObservableCollection?
提问by Scott Lawrence
I have an instance of ObservableCollection bound to a WPF listbox with two separate data templates (one for display, one for editing). The data template for editing has a one-way binding on the textbox, and a Save button.
我有一个绑定到 WPF 列表框的 ObservableCollection 实例,其中有两个单独的数据模板(一个用于显示,一个用于编辑)。用于编辑的数据模板在文本框上有一个单向绑定和一个保存按钮。
What changes do I need to make so that when I press the Save button (after putting the list item in edit mode), the value I change the textbox to replaces the value in the ObservableCollection (and the display)?
我需要进行哪些更改,以便当我按下“保存”按钮(将列表项置于编辑模式后)时,我更改文本框的值会替换 ObservableCollection(和显示)中的值?
采纳答案by Alan Mendelevich
Items in your collection should be of type that implements INotifyPropertyChanged interface. This way your list box will be notified that property value in your single item object has changed. ObservableCollection raises CollectionChanged event only when collection changes (items added, removed, etc.)
集合中的项目应该是实现 INotifyPropertyChanged 接口的类型。这样您的列表框将被通知您的单个项目对象中的属性值已更改。ObservableCollection 仅在集合更改(添加、删除项目等)时引发 CollectionChanged 事件
Quote from the MSDN library article on ObservableCollection
引自 MSDN 库文章 ObservableCollection
To fully support transferring data values from binding source objects to binding targets, each object in your collection that supports bindable properties must implement an appropriate property changed notification mechanism such as the INotifyPropertyChanged interface.
要完全支持将数据值从绑定源对象传输到绑定目标,集合中支持可绑定属性的每个对象都必须实现适当的属性更改通知机制,例如 INotifyPropertyChanged 接口。
回答by CSharper
For change notification to occur in a binding between a bound client and a data source, your bound type should either:
要在绑定客户端和数据源之间的绑定中发生更改通知,您的绑定类型应该:
- Implement the INotifyPropertyChanged interface (preferred).
- Provide a change event for each property of the bound type.
- 实现 INotifyPropertyChanged 接口(首选)。
- 为绑定类型的每个属性提供一个更改事件。
Do not do both.
不要两者都做。
回答by accessD
I've solved similar problem using BindingList<T> class.
我已经使用 BindingList<T> 类解决了类似的问题。
It has ListChanged event fired both on collection and individual item change.
它在集合和单个项目更改时都触发了 ListChanged 事件。
Introduced in .Net 3.5
在 .Net 3.5 中引入