这是我想出并认为我会分享的解决方案:
首先,我们需要一个转换器来识别我们所在的树的级别(对此答案的代码稍作修改):
public class TreeLevelConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var level = -1;
if (value is DependencyObject)
{
var parent = VisualTreeHelper.GetParent(value as DependencyObject);
while (!(parent is TreeView) && (parent != null))
{
if (parent is TreeViewItem)
level++;
parent = VisualTreeHelper.GetParent(parent);
}
}
return (parameter?.ToString() ?? "") + ((char)('A' + level)); // the group name has to be a letter, numbers didn't work
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new System.NotImplementedException();
}
}
比我们可以在 XAML 中使用绑定:
<TreeView ItemsSource="{Binding MyItems}" Grid.IsSharedSizeScope="True">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Grid}}, Converter={StaticResource TreeLevelConverter}, ConverterParameter=A}"/>
<ColumnDefinition Width="Auto" SharedSizeGroup="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Grid}}, Converter={StaticResource TreeLevelConverter}, ConverterParameter=B}"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="{Binding Value}" Grid.Column="1"/>
</Grid>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
使用转换器参数,您可以在一个级别内实现多个组。
我希望这会对某人有所帮助