Given the Question:-
so when I click a node, how do I know which level it is? is there workaround?
Here's a possible workaround:-
If you have a reference to a Control in the Visual Tree, possibly from a Click
event then you can use that control to work out which level it is in the tree view by calling a function like this, that I've used in the past.
private int FindTreeLevel(DependencyObject control)
{
var level = -1;
if (control != null)
{
var parent = VisualTreeHelper.GetParent(control);
while (!(parent is TreeView) && (parent != null))
{
if (parent is TreeViewItem)
level++;
parent = VisualTreeHelper.GetParent(parent);
}
}
return level;
}
This method will walk up the VisualTree and count how many TreeViewItem
controls it finds before stopping when it finds the TreeView
Control.
If you need this available in XAML, for example, a DataTrigger
of a HierarchicalDataTemplate
then you could package this up in to a IValueConverter
class
<Window.Resources>
<local:TreeLevelConverter x:Key="treeLevelConverter"/>
<HierarchicalDataTemplate DataType="{x:Type local:MyType}" >
...
<Grid ... >
<TextBlock x:Name="MyControl" ... />
...
</Grid>
<HierarchicalDataTemplate.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource treeLevelConverter}}" Value="0" >
<Setter TargetName="MyControl" Property="Background" Value="Red"/>
</DataTrigger>
</HierarchicalDataTemplate.Triggers>
</HierarchicalDataTemplate>
</Window.Resources>
Then use the following Converter
public class TreeLevelConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var level = -1;
if (value is DependencyObject )
{
var parent = VisualTreeHelper.GetParent(value as DependencyObject );
while (!(parent is TreeView) && (parent != null))
{
if (parent is TreeViewItem)
level++;
parent = VisualTreeHelper.GetParent(parent);
}
}
return level;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new System.NotImplementedException();
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…