I have the need to adjust the margin of my treeviewitems according to the height of the parent treeviewitem. I tried to add a converter to the stackpanel in the hierarchicaldatatemplate but it doesn't开发者_如何学运维 give me any way to accessing the treeviewitem in the converter convertTo method.
<UserControl.Resources>
<converter:LocationConverter x:Name="LocationConverter1" x:Key="LocationConverter1" />
<sdk:HierarchicalDataTemplate x:Key="DataTemplate1" ItemsSource="{Binding SubCategory}">
<StackPanel Margin="{Binding Converter={StaticResource LocationConverter1}}">
<TextBlock Text="{Binding Name}" />
</StackPanel>
</sdk:HierarchicalDataTemplate>
</UserControl.Resources>
<Grid x:Name="LayoutRoot">
<custom:TreeViewExtended x:Name="TopicsTreeView"
HorizontalAlignment="Left"
VerticalAlignment="Top"
ItemTemplate="{StaticResource DataTemplate1}"/>
<Button Content="Add" Click="Button_Click" Margin="200"></Button>
</Grid>
Is there any way of passing the treeView instance as a converterParameter into the convertTo method so I can find the treeviewitems by name from within the converter method?
Thanks
I don't know of a good way to put the TreeView instance as a ConverterParameter (Googling ConverterParameter yields some interesting ideas on how to achieve this...), but I think your approach is wrong - instead of passing the entire tree view to the converter and then find TreeViewItems by name, why not pass the TreeViewItem to the Margin binding with a converter that will search the visual tree and find the required height?
This can be done like this:
<StackPanel Margin="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType=TreeViewItem},
Converter={StaticResource LocationConverter1}}">
Now, your converter's value parameter will be the current TreeViewItem. From this value, you can get the TreeView instance or, even better, the parent TreeViewItem (if such exist) using the VisualTreeHelper.
精彩评论