Accessing the children of an expander control

后端 未结 2 792
有刺的猬
有刺的猬 2021-01-23 22:24

I have a textblock inside the ContentTemplate of an Expander. I want to access that textblock in my code behind file. This is what I have tried so far



        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-23 22:52

    I've tried your code, it's almost fine. I've tried testing it on such as a Button first, it works OK. However for the Expander, it's more complex. There are 2 notices here:

    • Be sure the Expander is expanded (IsExpanded = true).
    • Be sure the layout is updated (you can call UpdateLayout explicitly)

    So the code should be:

    yourExpander.IsExpanded = true;
    yourExpander.UpdateLayout();
    //now use your method
    var textBlock = FindVisualChild(yourExpander);
    

    Your code can be shorten more like this:

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

    Note that child will never be null. Because the GetChildrenCount() already limits the range of existing children, so the child should exist at the specified index i.

提交回复
热议问题