修改 ItemsSource ObservableCollection 后如何刷新组合框
问题很简单:更新 ItemsSource
时,组合框不会“刷新”,例如,新项目似乎没有添加到组合框中的项目列表中。
我已经尝试过此问题的接受答案中的解决方案:WPF - 自动刷新组合框内容 没有运气。
这是我的代码, XAML:
<ComboBox Name="LeadTypeComboBox" ItemsSource="{Binding LeadTypeCollection}" />
ViewModel:
public ObservableCollection<XmlNode> LeadTypeCollection { get; set; }
我更新此集合的方式是在单独的方法中,该方法从更新的 XML 文件加载数据: this.LeadTypeCollection = GetLeadTypesDataSource();
我也尝试过使用 Add< /code> 用于测试目的:
this.LeadTypeCollection = GetLeadTypesDataSource();
ItemToAdd = LeadTypeCollection[LeadTypeCollection.Count - 1];
this.LeadTypeCollection.Add(ItemToAdd);
代码更新集合肯定会开始,调试时我可以在该集合中看到新项目,但在组合框中看不到它们。
在 xaml 代码隐藏中执行此操作: LeadTypeComboBox.ItemsSource = MyViewModel.GetLeadTypesDataSource();
但我想使用 MVVM 来实现此目的,即代码必须位于不知道的 ViewModel 中LeadTypeComboBox 控件的。
The problems is simple: when ItemsSource
is updated Combobox doesn't "refresh" e.g. new items don't appear to be added to the list of items in the combobox.
I've tried the solution from aceepted answer to this question: WPF - Auto refresh combobox content with no luck.
here's my code,
XAML:
<ComboBox Name="LeadTypeComboBox" ItemsSource="{Binding LeadTypeCollection}" />
ViewModel:
public ObservableCollection<XmlNode> LeadTypeCollection { get; set; }
the way I update this collection is in the separate method, which loads data from updated XML file: this.LeadTypeCollection = GetLeadTypesDataSource();
I've also tried using Add
for testing purposes:
this.LeadTypeCollection = GetLeadTypesDataSource();
ItemToAdd = LeadTypeCollection[LeadTypeCollection.Count - 1];
this.LeadTypeCollection.Add(ItemToAdd);
the code updating collection definitely kicks off, I can see new items in this collection when debugging, but I don't see them in the combobox.
Doing this in the xaml code-behind works: LeadTypeComboBox.ItemsSource = MyViewModel.GetLeadTypesDataSource();
but I'd like to achieve this with MVVM, i.e. the code must be in ViewModel which isn't aware of LeadTypeComboBox control.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Firedragons 的答案会起作用,但我更愿意只初始化一次 LeadTypeCollection 并使用清除、添加删除来更新您的集合。
如果数据上下文正确,您的 xaml 绑定应该可以工作
Firedragons answer would work, but i would prefer to initialize the LeadTypeCollection just once and use clear, add remove to update your collection.
your xaml binding should work if the datacontext is right
我想我以前见过这种情况,解决方案是更新集合属性以引发更改。
即
我有一个用于提升属性的扩展方法(如 stackoverflow 上其他地方所示):
I think I have seen this before and the solution was to update the collection property to raise the change.
i.e.
I have an extension method for raising the property (as found elsewhere on stackoverflow):
一个简单的方法是将 ItemsSource 更改为空列表,然后将其更改回更新的源。我正在运行的项目的片段:
A simple method is to change ItemsSource with empty list and then change it back to your updated source. A snippet from my project which is working: