wpfvisualtreehelper

How to get the child control inside a TreeviewItem?


I customed my TreeViewItem to be a StackPanel with image and textblock inside; I'd like to get a reference to the TextBlock inside. For the codes below node is of type TreeviewItem and I am surechildrenCound =3 which could be StackPanel image textblock! But it can not find any TextBlock inside. I never see any console output and object _itemToMovereturns null

TreeViewItem node = UIHelper.FindVisualParent<TreeViewItem>(e.OriginalSource as FrameworkElement);
var child = VisualTreeHelper.GetChild(node, 0);
int childrenCount = VisualTreeHelper.GetChildrenCount(child);
for (int i = 0; i < childrenCount; i++)
{
    TextBlock vc = VisualTreeHelper.GetChild(child, i) as TextBlock;
    if (vc != null)
    {
        Console.WriteLine("ggggggggggggggggggggggggggggggggggggggggggggggg");

        _itemToMove = vc.Text as object;
    }

}
Console.WriteLine(childrenCount+";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;");

Solution

  • It may be that your TextBlock is buried deeper than you think. I've always had success using the following helper which is generic enough to be used elsewhere in the app.

    public static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
    {
        if (obj != null)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                var child = VisualTreeHelper.GetChild(obj, i);
                if (child is T)
                {
                   return (T)child;
                }
    
                T childItem = FindVisualChild<T>(child);
                if (childItem != null) return childItem;
            }
        }
        return null;
    }
    

    I think I got this from a similar question from StackOverflow.