它的工作了几个小时后,我发现使用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>
第一中multibinding结合获取ScrollContentPresenter
在TreeView
宽度,这是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();
}
}
现在,这是正确的样子:
alt text http://img249.imageshack.us/img249/6889/atts2.png
感谢此代码。这适用于我! 干杯! – klaydze 2015-09-28 00:37:21
完美适合我:) – 2015-10-25 11:40:05