如何在单个级别而不是多个级别中共享“网格”列的大小?
<TreeView ItemsSource="{Binding MyItems}" Grid.IsSharedSizeScope="True">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="A"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="{Binding Value}" Grid.Column="1"/>
</Grid>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
这种作品,但是在整个树之间共享大小,这不是我想要的
答案 0 :(得分:0)
这是我想出并认为可以分享的解决方案:
首先,我们需要一个转换器来标识我们所在的树的级别(this answer中经过稍微修改的代码):
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>
使用转换器参数,可以在一个级别内实现多个组。
我希望这会对某人有所帮助