它的工作了幾個小時後,我發現使用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