使用 MVVM 将 IList 绑定到列表控件
我正在尝试理解 MVVM 模式,并且我使用了一个示例程序来进行工作。该模型是一个 C# .net 库,查询时返回一个 IList
对象。我希望我的视图能够通过数据绑定添加/编辑/删除此集合中的项目。但我不知道如何使用 MVVM 开始。请帮帮我。
模型公开一个接口来检索 IList
对象, View 有一个列表框,显示 IList
的内容,以及几个其他控件,用于将数据添加到 IList
。
I am trying to understand MVVM pattern and I took a sample program to work on. The model is a C# .net library which when queried returns an IList<INote>
object. I want my view to be able to add/edit/delete items in this collection through data binding. But I don't know how to start with this, using MVVM. Please help me out.
Model exposes an interface to retrieve the IList<INote>
objecs,
View has a list box showing the contents of IList<INote>
and couple of other controls to add data to the IList<INote>
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将您的 ListBox 绑定到
ObservableCollection
,每次您在该ObservableCollection
中添加或删除某些内容时,它都会立即更新。此
ObservableCollection
通常应该是 ViewModel 的属性。如果模型中的并使用存储库添加/删除项目并相应地同步。
IList
属性不可观察(并且您无法控制它),则必须编写代码以在 ViewModel 中同步它。这些都是建筑学的问题。我认为在这方面最干净的选择是实际使用 ReadOnlyObservableCollectionBind your ListBox to an
ObservableCollection<T>
and it will instantly be updated everytime you add or remove something from thatObservableCollection<T>
.This
ObservableCollection<T>
should normally be a property of your ViewModel.If the
IList
property from your Model is not observable (and you don't have control over it), you will have to write the code to synchronize it within your ViewModel. These are questions of architecture then. I feel the cleanest choice in this regard is to actually use aReadOnlyObservableCollection<T>
and add / remove items using your repository and synchronize accordingly.我关于
DelegateCommand
的博客文章应该给你一个良好的基础。My blog post on
DelegateCommand
should give you a good grounding.我将列表框绑定到
ObservableCollection
,并在该集合中添加/删除/修改项目。效果很好。看看它是如何实现的无需任何 INotifyPropertyChanged 即可工作。如果我错了请纠正我I bind my list box to an
ObservableCollection<Item>
and I added/removed/modified items into and out of this collection. It works fine. Check this out on how it works without any INotifyPropertyChanged. Please correct me if I am wrong