Windows 8 metro app collectionviewsource data binding problem

I have a collectionviewsource

<CollectionViewSource x:Name="groupedItemsViewSource" ItemsPath="Items" /> 

and pass it as source items in gridview

 ItemsSource="{Binding Source={StaticResource groupedItemsViewSource}}" 

the source is specified in the code behind the file:

 groupedItemsViewSource.Source = AllGroups; 

and allgroups

 public ObservableCollection<DataGroup> AllGroups 

where the DataGroup contains a collection of Observable elements

  public ObservableCollection<DataItem> Items 

the problem is that it does not display groups with elements, instead I get only 3 gridviewitems that correspond to 3 data groups in AllGroups

I tried to add IsSourceGroupped = "true", but when I do this, the application crashes, a window appears that says: "Fixed win32 exception in myapp.exe [3192]"

+4
source share
2 answers

The Source property in CollectionViewSource must implement the IGrouping interface, otherwise the groups will not work in the GridView or ListView.
Either use the Linq GroupBy expression to group the results into groups with the specified key, or you can extend the ObservableCollection class as follows:

 public class GroupedObservableCollection<T> : ObservableCollection<T>, IGrouping<string, T> { /// <summary> /// Key as the Group identificator. /// </summary> public string Key { get; set; } } 

and use it in my class (I have a CollectionViewSource in ViewModel, not in XAML):

 public GroupedObservableCollection<DataItem> Items groupedItemsViewSource = new CollectionViewSource { Source = AllGroups, ItemsPath = new PropertyPath("Items"), IsSourceGrouped = true }; 

This way the binding will work. Also make sure you use the correct bindings in ListView and GridView:

 <!-- zoomed in view --> <GridView ItemsSource="{Binding groupedItemsViewSource.View}" ... /> <!-- zoomed out view --> <GridView ItemsSource="{Binding groupedItemsViewSource.View.CollectionGroups}" ... /> 
0
source

It looks like all you are missing is the IsSourceGrouped = "true" attribute in CollectionViewSource.

0
source

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


All Articles