In a WinForms application, the level of a treeview is given by node.level
What is the corresponding one in WPF?
Thanks!
In a WinForms application, the level of a treeview is given by node.level
What is the corresponding one in WPF?
Thanks!
The direct answer to your question is that there is no level property in WPF.
There is no one to one relationship between the winforms controls and wpf control. Because the underlying architecture and usage is totally different in both. In WPF you will bind a heirarchical data(LinkedList kind of Datastructure) to a TreeView and define a HeirarchicalDataTemplate to the Treeview.ItemTemplate property
so when I click a node, how do I know which level it is? is there workaround? I will display different contents based on the level and node header.
Thanks!
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();
}
}