简体   繁体   中英

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?

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!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM