How do you get the level of a treeviewitem in WPF C#?

前提是你 提交于 2019-12-05 21:45:43
Aran Mulholland

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!