Iterate through CompositeCollection elements

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 the list shows the correct data in the graphical interface

I need this data (without reference to ListBox), and I do not get it

+4
source share
3 answers

Try the following: foreach (var itm in cmpc.Cast<CollectionContainer>().SelectMany(x => x.Collection.Cast<string>()))

+4
source

you should extract data from cmpc elements and set them as a data source as list.ItemsSource will not understand that you need to set internal elements of elements as a data source
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 the datasource resource

 list.ItemsSource = GetData(cmpc); 
+1
source

ListBox uses the default view of the collection for its ItemsSource property, which you can also use:

  foreach (string itm in CollectionViewSource.GetDefaultView(cmpc)) { Debug.Print(itm); } 

You can use the ICollectionView classes to sort or filter ItemsSource , but be careful until it works with CompositeCollection s, as you can see this question: How to handle CompositeCollection elements with CollectionView functions?

+1
source

Source: https://habr.com/ru/post/1312301/


All Articles