经过几个小时的研究,我找到了一个使用Multibinding和两个转换器的可行解决方案。
一、XAML中HierarchicalDataTemplate的定义:
<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>
多重绑定中的第一个绑定获取TreeView中ScrollContentPresenter的宽度,即TreeView的总可见宽度。第二个绑定以TreeViewItem 作为参数调用转换器,并计算TreeViewItem 在到达根项之前有多少父项。使用这两个输入,我们使用 Multibinding 中的 SumConverterInstance 来计算给定 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();
}
}
现在是正确的样子: