迭代 CompositeCollection 的项目
考虑代码:
ObservableCollection<string> cities = new ObservableCollection<string>();
ObservableCollection<string> states = new ObservableCollection<string>();
ListBox list;
cities.Add("Frederick");
cities.Add("Germantown");
cities.Add("Arlington");
cities.Add("Burbank");
cities.Add("Newton");
cities.Add("Watertown");
cities.Add("Pasadena");
states.Add("Maryland");
states.Add("Virginia");
states.Add("California");
states.Add("Nevada");
states.Add("Ohio");
CompositeCollection cmpc = new CompositeCollection();
CollectionContainer cc1 = new CollectionContainer();
CollectionContainer cc2 = new CollectionContainer();
cc1.Collection = cities;
cc2.Collection = states;
cmpc.Add(cc1);
cmpc.Add(cc2);
list.ItemsSource = cmpc;
foreach(var itm in cmpc)
{
// itm is CollectionContainer and there are only two itm’s
// I need the strings
}
虽然列表在 GUI 上显示了正确的数据,但
我需要此数据(不引用列表框),但我没有得到它
Consider the code:
ObservableCollection<string> cities = new ObservableCollection<string>();
ObservableCollection<string> states = new ObservableCollection<string>();
ListBox list;
cities.Add("Frederick");
cities.Add("Germantown");
cities.Add("Arlington");
cities.Add("Burbank");
cities.Add("Newton");
cities.Add("Watertown");
cities.Add("Pasadena");
states.Add("Maryland");
states.Add("Virginia");
states.Add("California");
states.Add("Nevada");
states.Add("Ohio");
CompositeCollection cmpc = new CompositeCollection();
CollectionContainer cc1 = new CollectionContainer();
CollectionContainer cc2 = new CollectionContainer();
cc1.Collection = cities;
cc2.Collection = states;
cmpc.Add(cc1);
cmpc.Add(cc2);
list.ItemsSource = cmpc;
foreach(var itm in cmpc)
{
// itm is CollectionContainer and there are only two itm’s
// I need the strings
}
While list shows the right data on the GUI
I need this data (without referring to the ListBox) and I am not getting it
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个: foreach (var itm in cmpc.Cast().SelectMany(x => x.Collection.Cast()))
Try this:
foreach (var itm in cmpc.Cast<CollectionContainer>().SelectMany(x => x.Collection.Cast<string>()))
ListBox
为其ItemsSource
属性使用集合的默认视图,您也可以使用它:您可以使用
ICollectionView
类进行排序或过滤ItemsSource
,但要小心,这不能与CompositeCollection
一起正常工作,正如您可以看到这个问题:如何使用 CollectionView 功能处理 CompositeCollection?The
ListBox
uses for itsItemsSource
Property the default view of the collection, which you can use, too:You can use the
ICollectionView
classes to sort or filter anItemsSource
, but be careful while this won't work properly withCompositeCollection
s, as you can see this question: How to handle a CompositeCollection with CollectionView features?您应该从 cmpc 项目中提取数据并将其设置为列表数据源。ItemsSource 不会理解您需要将项目的内部项目设置为数据源
编辑
您可以使用此方法
并设置数据源
you should extract data from cmpc items and set them as data source as list.ItemsSource won't understand that u need to set inner items of items as a datasource
EDIT
You can use this method
and set datasource