经过几个小时的研究,我找到了一个使用Multibinding和两个 Converters的工作解决方案。
一、HierarchicalDataTemplate
XAML中的定义:
<HierarchicalDataTemplate>
<Grid>
<Grid.Width>
<MultiBinding Converter="{StaticResource SumConverterInstance}">
<Binding RelativeSource="{RelativeSource FindAncestor, AncestorType=ScrollContentPresenter, AncestorLevel=1}" Path="ActualWidth" />
<Binding RelativeSource="{RelativeSource FindAncestor, AncestorType=TreeViewItem, AncestorLevel=1}" Converter="{StaticResource ParentCountConverterInstance}" />
</MultiBinding>
</Grid.Width>
.... (content of the template) ....
</Grid>
</HierarchicalDataTemplate>
multibinding 中的第一个绑定获取 in 的宽度ScrollContentPresenter
,TreeView
即 的总可见宽度TreeView
。第二个绑定以 为参数调用转换器,并计算在到达根项之前有TreeViewItem
多少父项。TreeViewItem
使用这两个输入,我们使用 SumConverterInstanceMultibinding
来计算给定的可用宽度TreeViewItem
。
以下是 XAML 中定义的转换器实例:
<my:SumConverter x:Key="SumConverterInstance" />
<my:ParentCountConverter x:Key="ParentCountConverterInstance" />
以及两个转换器的代码:
// combine the width of the TreeView control and the number of parent items to compute available width
public class SumConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
double totalWidth = (double)values[0];
double parentCount = (double)values[1];
return totalWidth - parentCount * 20.0;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
// count the number of TreeViewItems before reaching ScrollContentPresenter
public class ParentCountConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
int parentCount = 1;
DependencyObject o = VisualTreeHelper.GetParent(value as DependencyObject);
while (o != null && o.GetType().FullName != "System.Windows.Controls.ScrollContentPresenter")
{
if (o.GetType().FullName == "System.Windows.Controls.TreeViewItem")
parentCount += 1;
o = VisualTreeHelper.GetParent(o);
}
return parentCount;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
现在是正确的外观: