我想通过以下分组制作DataGrid
我的问题是如何在群组标题中执行“平均值”?
下面是一个巨大的xaml
<DataGrid x:Name="dataGrid" Grid.Column="1" CanUserResizeRows="False" CanUserSortColumns="False" GridLinesVisibility="None" AutoGenerateColumns="False" ItemsSource="{Binding List}" HeadersVisibility="Column" Grid.IsSharedSizeScope="True">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding A}" Header="A"/>
<DataGridTextColumn Binding="{Binding B}" Header="B"/>
<DataGridTextColumn Binding="{Binding C}" Header="C"/>
<DataGridTextColumn Binding="{Binding Group}" Header="Group"/>
</DataGrid.Columns>
<DataGrid.GroupStyle>
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="GroupItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="GroupItem">
<Border BorderBrush="Gray" BorderThickness="0.5" CornerRadius="4" Margin="3">
<Border.Background>
<LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5">
<GradientStop Color="#FFACACAC" Offset="0"/>
<GradientStop Color="White" Offset="1"/>
</LinearGradientBrush>
</Border.Background>
<StackPanel>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition SharedSizeGroup="A"/>
<ColumnDefinition SharedSizeGroup="B"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Name}" Margin="10,0,10,0"/>
<TextBlock Grid.Column="1" Text="{Binding ItemCount}" Margin="10,0,0,0"/>
<TextBlock Grid.Column="2" Text="test" Margin="10,0,0,0"/>
</Grid>
<Expander>
<Border BorderBrush="Gray" BorderThickness="0.5" Margin="3">
<ItemsPresenter/>
</Border>
</Expander>
</StackPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</DataGrid.GroupStyle>
</DataGrid>
产生此输出
我可以输出组名(绿色箭头)和计数器(红色箭头)。
如何输出任一列的平均值(让它为A
)而不是“test”?
答案 0 :(得分:1)
您需要使用转换器将Items
属性转换为平均值。像这样:
public class ItemsToAverageConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter,
CultureInfo culture){
var propName = Convert.ToString(parameter);
var items = (IEnumerable<Item>) value;
var prop = typeof(Item).GetProperty(propName);
if(prop == null) return Binding.DoNothing;
return items.Average(i => (double) prop.GetValue(i));
}
public object Convert(object value, Type targetType, object parameter,
CultureInfo culture){
throw new NotImplementedException();
}
}
我认为项目类型为Item
。您在XAML代码中使用该转换器,可能需要一些StringFormat
来格式化值表示。
假设您在某处可访问此资源:
<local:ItemsToAverageConverter x:Key="avgConverter"/>
代码应该像这样改变:
<TextBlock Grid.Column="1" Text="{Binding Items,
Converter={StaticResource avgConverter},
ConverterParameter=A,
StringFormat=f2}" Margin="10,0,0,0"/>