Mathieu Guindon
Mathieu Guindon

Reputation: 71227

How to specify GroupDescriptions in XAML for a custom DataGrid control?

I have a GroupingGrid control that's basically a customized DataGrid. I got the groupings to work from code-behind, by making my ViewModel expose a ListCollectionView, and have C# code to manually add the PropertyGroupDescription that tells the grid how to regroup things.

I'd like to do that in plain XAML instead, like this:

<controls:GroupingGrid GroupedItemSource="{DynamicResource MyViewSource}"
                       SelectedItem="{Binding MySelectedItem}"
                       ShowGroupingItemCount="True">
    <DataGrid.Resources>
        <CollectionViewSource x:Key="MyViewSource" Source="{Binding ViewModel.MyData}">
            <CollectionViewSource.GroupDescriptions>
                <PropertyGroupDescription PropertyName="SomeProperty" 
                                          Converter="{StaticResource MyConverter}" />
            </CollectionViewSource.GroupDescriptions>
        </CollectionViewSource>
    </DataGrid.Resources>
    <DataGrid.Columns>
        <!-- column definitions -->
    </DataGrid.Columns>

So I added this to my GroupingGrid control's code-behind:

public static readonly DependencyProperty GroupedItemSourceProperty =
    DependencyProperty.Register("GroupedItemSource", typeof (CollectionViewSource), typeof (GroupingGrid));

public CollectionViewSource GroupedItemSource
{
    get { return (CollectionViewSource) GetValue(GroupedItemSourceProperty); }
    set { SetValue(GroupedItemSourceProperty, value); }
}

It builds, but I get a runtime XamlObjectWriterException saying:

Set property 'System.Windows.ResourceDictionary.DeferrableContent' threw an exception.

So basically, I can't use DataGrid.Resources in the "client xaml" to add things like a CollectionViewSource.GroupDescriptions collection, because I cannot re-initialize resource dictionary instance.

Is my only hope to define the groupings in C# code, or there's a neat XAML way?

Upvotes: 3

Views: 1166

Answers (1)

Subru
Subru

Reputation: 353

Add CollectionViewSource as Resource of Window/Usercontrol

<Window.Resources>
    <CollectionViewSource x:Key="MyViewSource" Source="{Binding ViewModel.MyData}">
        <CollectionViewSource.GroupDescriptions>
            <PropertyGroupDescription PropertyName="SomeProperty" 
                                      Converter="{StaticResource MyConverter}" />
        </CollectionViewSource.GroupDescriptions>
    </CollectionViewSource>
</Window.Resources>

Bind it to your DataGrid as follows

<DataGrid ItemsSource="{Binding Source={StaticResource MyViewSource}}"
          SelectedItem="{Binding MySelectedItem}"/>

Hope this helps!!

Upvotes: 3

Related Questions