Reputation: 435
SUMMARY: After removing grouping have items in a data grid sort.
So I currently have a project with a user control that displays one of two controls depending on a datatype. Now when that control is a DataGrid, I have set up a style on the template that uses grouping.
<!--STYLE used to add grouping & expanders to data grid-->
<Style x:Key="GroupHeaderStyle" TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander IsExpanded="False" >
<Expander.Header>
<TextBlock Text="{Binding Name}" TextDecorations="Underline"/>
</Expander.Header>
<ItemsPresenter/>
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
And it's set up in the model like this so that the grouping is done on a property called "Group".
Data = new ListCollectionView(rows);
Data.GroupDescriptions.Add(new PropertyGroupDescription("Group"));
Now the user can toggle a toggle button to remove headings, and therefore just show a list of values.
public bool IsGrouped
{
get { return isGrouped; }
set
{
isGrouped = value;
OnPropertyChanged();
if (ConfigurationModel != null)
{
if (IsGrouped == true)
(ConfigurationModel as ConfigurationKeyPairModel).AddGrouping();
else
(ConfigurationModel as ConfigurationKeyPairModel).RemoveGrouping();
}
}
}
public void RemoveGrouping()
{
if(Data.GroupDescriptions.Count > 0)
Data.GroupDescriptions.RemoveAt(0);
}
public void AddGrouping()
{
if(Data.GroupDescriptions.Count < 1)
Data.GroupDescriptions.Add(new PropertyGroupDescription("Group"));
}
Once the grouping has been removed the item's go back to how you'd expect just a normal data grid. But they're still in the same positions they would have been in if they were grouped. I don't want to have the user manually click column headers(which are hidden anyway) I'd like to have this data sort itself straight away. I've had a look around for the past hour but haven't found any decent solutions that are MVVM or don't just have the user click column headers.
Upvotes: 0
Views: 40
Reputation: 169340
You could sort the CollectionView
by a property by adding a SortDescription
to its SortDescriptions
property:
public void RemoveGrouping()
{
if (Data.GroupDescriptions.Count > 0)
Data.GroupDescriptions.RemoveAt(0);
Data.SortDescriptions.Clear();
Data.SortDescriptions.Add(new SortDescription("PropertyName", ListSortDirection.Ascending));
}
If there are no SortDescriptions
added, the sort order is effectively undefined.
Upvotes: 1