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
Try this: foreach (var itm in cmpc.Cast<CollectionContainer>().SelectMany(x => x.Collection.Cast<string>()))
The ListBox
uses for its ItemsSource
Property the default view of the collection, which you can use, too:
foreach (string itm in CollectionViewSource.GetDefaultView(cmpc))
{
Debug.Print(itm);
}
You can use the ICollectionView
classes to sort or filter an ItemsSource
, but be careful while this won't work properly with CompositeCollection
s, as you can see this question: How to handle a CompositeCollection with CollectionView features?
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
List<string> GetData(CompositeCollection cmpc)
{
List<string> allStrings = new List<string>();
foreach (var item in cmpc)
{
allStrings.AddRange(item.OfType<string>());
}
return allStrings;
}
and set datasource
list.ItemsSource = GetData(cmpc);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With