这就是你真正想要的。
首先编辑 GroupStyle HeaderTemplate
<GridView.GroupStyle>
<GroupStyle HidesIfEmpty="True">
<GroupStyle.HeaderTemplate>
<DataTemplate>
<Grid Width="500" Margin="5,0,0,5">
<TextBlock HorizontalAlignment="Left">
<Run Text="{Binding Name}" />
<Run FontFamily="Segoe Ui Symbol" Text="" />
</TextBlock>
<TextBlock HorizontalAlignment="Right">
<Run Text="{Binding Children.Count, FallbackValue=0}" />
<Run Text="Items" />
</TextBlock>
</Grid>
</DataTemplate>
</GroupStyle.HeaderTemplate>
<GroupStyle.Panel>
<ItemsPanelTemplate>
<VariableSizedWrapGrid />
</ItemsPanelTemplate>
</GroupStyle.Panel>
</GroupStyle>
</GridView.GroupStyle>
请注意我正在使用VaraibleSizedWrapGrid
接下来,处理 GridView 的 Loaded 事件
class SubtractConverter : IValueConverter
{
public double Amount { get; set; }
public object Convert(object v, Type t, object p, string l)
{ return System.Convert.ToDouble(v) - Amount; }
public object ConvertBack(object v, Type t, object p, string l)
{ throw new NotImplementedException(); }
}
private void GridView_OnLayoutUpdated(object sender, RoutedEventArgs e)
{
var grid = sender as GridView;
var converter = new SubtractConverter { Amount = 5 * 2 /* padding x2 */ };
foreach (GroupItem group in (grid.ItemsPanelRoot as Panel).Children)
{
var result = VisualTreeHelper.GetChild(group, 0);
while (!(result is Grid))
result = VisualTreeHelper.GetChild(result, 0);
var items = (result as Panel).Children.OfType<ItemsControl>()
.First().ItemsPanelRoot;
var binding = new Binding
{
Path = new PropertyPath("ActualWidth"),
Mode = BindingMode.OneWay,
Converter = converter,
Source = items,
};
var header = (result as Panel).Children.OfType<ContentControl>()
.First().ContentTemplateRoot as FrameworkElement;
header.SetBinding(FrameworkElement.WidthProperty, binding);
}
}
而且,快!现在,您的标题的大小与组中项目的宽度完美匹配。
要记住的事情(作为设计师):
- 您的分组项目可能与单个列一样窄。
TextTrimming
在 Header TextBox
es中解决这个问题。
- 您的分组项目可能比显示器宽,并且
# items
可能不在屏幕上。使用包含的 MinWidth 解决此问题grid
。
祝你好运!