[英]WPF TreeView share size of grid column in single level
How to share size of Grid column within single level instead of multiple levels? 如何在单个级别而不是多个级别内共享Grid列的大小?
<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>
This kind of works, but shares the size between the whole tree, which isn't what I wanted 这种作品,但在整个树之间共享大小,这不是我想要的
Here is the solution that I came up with and thought I would share: 这是我想到并想分享的解决方案:
First, we need a converter to identify the level of tree that we are in (slightly modified code from 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();
}
}
than we can use binding in XAML: 比我们可以在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>
Using the converter parameter you can achieve multiple groups within one level. 使用转换器参数,可以在一个级别内实现多个组。
I hope this will help someone 我希望这会帮助某人
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.