I’m fairly new to MVVM, and I have recently started a project cleaning up my codebehind and bit by bit I am moving everything to Model and ViewModel.
My problem is, now, how do you use grouping using Collection View without any code behind? I thought I had figured it out, after reading answers to similar questions here on Stackoverflow, but I still can’t get it to work. Probably a silly mistake, but I would be very grateful if somebody could have a look at my code and let me know what they think. All feedback is great feedback, I really want to become a good programmer 🙂
The list is btw of the type ObservableCollection in the Menu class.
<CollectionViewSource x:Key="foods" Source="{Binding Items}">
<CollectionViewSource.GroupDescriptions>
<PropertyGroupDescription PropertyName="Category"/>
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
<ListBox x:Name="selectedMenuItem" Foreground="White" Grid.Column="0" Grid.Row="1" ItemsSource="{Binding Source={StaticResource foods}}"
DisplayMemberPath="Name" Background="{x:Null}" BorderThickness="0">
<ListBox.GroupStyle>
<x:Static Member="GroupStyle.Default"/>
</ListBox.GroupStyle>
</ListBox>
private CollectionViewSource _items;
private Menu _menu = new Menu();
public ICollectionView Items
{
get
{
if (_items == null)
{
_items = new CollectionViewSource {Source = new ObservableCollection<MenuItem>(_menu.MyMenu)};
}
return _items.View;
}
}
I’m assuming your problem is that data doesn’t show up in your ListBox? Try programmatically adding your groupings to
_itemsand binding your ListBox.ItemsSource directly toItems:You can then do away with the
foodsresource, assuming I haven’t boffed my code.