问题
How do you get the level of a treeviewitem in WPF C#? In windows forms there is a .Level member of the treeview class but there does not seem to be one for WPF C#.
回答1:
Build a view model.
A View model gves you greater flexibility with the treeview than you can achieve without it. Do yourself a favour, dont walk the visual tree, If a parent node is not visible, it could be virtualised away and your level (or depth) figure will be wrong. build a view model that wraps your data and knows at what level it is at.
Check out the answers posted here.
answer link one (you would add another property to your view model - level)
treeview view model demo
回答2:
I did it with a converter because I wanted to do it with <style>
<DataTrigger Binding="{Binding Parent, RelativeSource={RelativeSource Self}, Converter={StaticResource TreeViewItemConverter}}" Value="1">
<Setter TargetName="Bd" Property="Background" Value="Yellow"/>
</DataTrigger>
And the converter
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if ((value as TreeView) != null)//level 1
return 0;
var item = (value as TreeViewItem);
if (item != null) // level 2 and 3
return (item.Parent as TreeViewItem)!=null ? 2 : 1;
return 0;
}
This is particularly useful for multilevel styling in the treeview
来源:https://stackoverflow.com/questions/3182359/how-do-you-get-the-level-of-a-treeviewitem-in-wpf-c