Search code examples
c#wpfvisibilitytreeviewitem

Actual position of collapsed TreeViewItem on Canvas


Is there a way to evaluate the actual position of a TreeViewItem on a Canvas if its Parent TreeViewItem is collapsed (meaning <ParentTreeViewItem>.IsExpanded = false;)? When debugging neither the Visibility nor the Position information of the collapsed item in the parent´s ItemsHost seems to be updated.

Appreciating any hint!

Cheers, Alex


Solution

  • Found a workaround for this problem:

    Basically whenever a TreeViewItem fires an OnCollapsed or OnExpanded event I force all other TreeViewItems to determine their own position based on the IsExpanded property of their ancestors up to the tree root.

    If any of the ancestors is collapsed (i. e. IsExpanded == false) I apply its position to the current TreeViewItems position.

    If none of the ancestors is collapsed, I apply its own position (whereas position is a custom Point property of the TreeViewItem).

    Code sample:

    private Point DeterminePosition()
        {
            Point point = this.position;
    
            if (ParentTreeViewItem != null)
            {
                MyTreeViewItem parent = null, lastCollapsed = null;
    
                parent = ParentTreeViewItem;
    
                while (parent != null)
                {
                    if (parent.IsExpanded == false)
                    {
                        lastCollapsed = parent;
                    }
    
                    parent = parent.ParentTreeViewItem;
                }
    
    
                if (lastCollapsed != null)
                {
                    point = new Point(position.X, lastCollapsed.Position.Y);
                }
    
            }
    
            return point;
        }