组合框项目源和所选项目同步
我有一个绑定到 ViewModel 中的 ObservableCollection
的组合框。当用户添加新项目时,我不知道他们是否已将项目添加到绑定集合中,因此我进行刷新。好吧,这将所选项目设置为空,因此我实现了一些代码来记住所选项目并在更新集合后设置它。问题是集合不显示所选项目。
if (_selectedBrand != null)
{
int selectedBrandID = _selectedBrand.BrandID;
Brands = null;
Brands = new ObservableCollection<Brand>(_dataContext.Brands.ToList());
SelectedBrand = _dataContext.Brands.First<Brand>(b => b.BrandID == selectedBrandID);
}
如何让集合显示更正后的项目?
编辑:该集合代表后端数据库中的一个表。用户可以打开一个新窗口将项目添加到数据库中。窗口关闭后,我必须刷新集合才能获取新项目。抱歉我的措辞混乱。
I have a combobox that is bound to ObservableCollection<Item>
in the ViewModel. When a user adds a new item I don't know if they've added an item to the bound collection so I do a refresh. Well this sets the selecteditem to null so I implemented some code to remember the selected item and set it after the Collection is renewed. The problem is the collection doesn't display the selecteditem.
if (_selectedBrand != null)
{
int selectedBrandID = _selectedBrand.BrandID;
Brands = null;
Brands = new ObservableCollection<Brand>(_dataContext.Brands.ToList());
SelectedBrand = _dataContext.Brands.First<Brand>(b => b.BrandID == selectedBrandID);
}
How can I get the collection to display the corrected item?
Edit: The collection represents a table in the backend DB. The user can open a new window to add items to the DB. Once the window is closed I must refresh the collection to get any new items. Sorry for the confusion of my wording.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您能否不只是检索新集合,然后更新现有集合并添加缺失值(使用 linq 扩展除外?)
Can you not just retrieve the new collection, and then update the existing one adding in the missing values (using the linq extension except?)
您将
SelectedBrand
设置为_dataContext.Brands
中的一个项目,该项目在Brands
ObservableCollection 中不存在。更改代码以将
SelectedBrand
设置为ObservableCollection
中的项目,而不是_dataContext
。You are setting your
SelectedBrand
to an item in your_dataContext.Brands
, which doesn't exist in theBrands
ObservableCollection.Change your code to set
SelectedBrand
to an item in yourObservableCollection
, not your_dataContext
.我假设这段代码位于按钮单击事件处理程序的上下文中?所以我不确定为什么你每次都必须重新初始化集合。您应该能够仅使用 Brands.Add 方法。我的工作场所没有 .net 3.5,所以我只需要对其进行伪编码。
我不知道这是否是您正在寻找的内容,但也许它会有所帮助。
I'm assuming this code is in the context of a Button Click eventhandler? So I'm not sure why you are havign to reinitialize the collection everytime. You should be able to just use the Brands.Add method. I don't have .net 3.5 at my workplace so I'll just have to psuedo code it.
I don't know if this is what you are looking for but maybe it can help.