WPF DataGrid Grouping with sums and other fields

前端 未结 1 2044
小鲜肉
小鲜肉 2020-12-06 07:28

I have a DataGrid that is bound to collection and that I want to be grouped. Here is the code

Collection:

private string _ID;
private string _Descri         


        
相关标签:
1条回答
  • 2020-12-06 07:53

    You could use a converter that's passed the Items property of the group header e.g.

    <Window.Resources>
        <local:GroupsToTotalConverter x:Key="groupsConverter" />
    </Window.Resources>
    
    <Expander.Header>
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding Path=Name}" Margin="5"/>
            <TextBlock Text="total" Margin="5" />
            <TextBlock Text="{Binding Path=Items, Converter={StaticResource groupsConverter}}" Margin="5" />
        </StackPanel>
    

    where the converter performs the calculation and passes back the total as the string for the text block:

    public class GroupsToTotalConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is ReadOnlyObservableCollection<Object>)
            {
                var items = (ReadOnlyObservableCollection<Object>)value;
                Decimal total = 0;
                foreach (GroupItem gi in items)
                {
                    total += gi.Amount;
                }
                return total.ToString();
            }
            return "";
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return value;
        }
    }
    

    As for the description I'd suggest also grouping by that, and writing another converter to pull out the description from the Items in a similar manner to above.

    0 讨论(0)
提交回复
热议问题