数据绑定到集合的一部分 [英] Data bind to a portion of a collection
问题描述
我的问题是如何将第二个ComboBox绑定到这些项目的一个子集。我想要的行为是将第二个ComboBox绑定到选择第一个ComboBox之后剩余的项目子集。例如,第一个ComboBox将显示1,2,3 ...,100。如果在第一个ComboBox中选择了43号,那么第二个ComboBox应该显示44,45,...,100。
如果第一个更改没有很多代码隐藏,ComboBox更新?
我将使用MVVM模式。
创建一个实现INotifyChange并显示三个属性的类。
- ICollection FullCollection
- int FirstIndex
- ICollection PartialCollection
将此类作为DataContext用于您的控件和将第一个组合框的SelectedIndex绑定到FirstIndex属性,将第一个组合框的ItemSource转换为FullCollection,将第二个Collection的ItemSource绑定到PartialCollection(确保SelectedIndex绑定模式是双向的)。
然后在FirstIndex属性集上,根据需要设置PartialCollection属性。
请记住,您必须在每个属性的set方法上使用NotifyPropertyChange。
希望这个帮助。
I have a static collection of items (say numbers from 1 to 100) that I'm presenting in a ComboBox. I can bind these items to the ComboBox no problem.
My question is how to bind a second ComboBox to a subset of those items. The behavior I want is to have the second ComboBox bound to the subset of items remaining after the first ComboBox is selected. For example the first ComboBox would show 1,2,3...,100. If the number 43 is selected in the first ComboBox then the second ComboBox should show 44,45,...,100.
How can this be accomplished and have the second ComboBox update if the first is changed without a lot of code-behind?
I would do this with a using MVVM pattern.
Create a class that implements INotifyChange and expose three Property.
- ICollection FullCollection
- int FirstIndex
- ICollection PartialCollection
Use this class as DataContext for your Control and bind SelectedIndex of the first combo box to FirstIndex property, ItemSource of first combobox to FullCollection and ItemSource of second collection to PartialCollection (Be sure that SelectedIndex binding mode is Two Way). Then on set of FirstIndex property set the PartialCollection property as you want. Remember that you have to use NotifyPropertyChange on set method of each Properties. Hope this help.
这篇关于数据绑定到集合的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!