How to get ListBox ItemsPanel in code behind

后端 未结 3 890
心在旅途
心在旅途 2020-12-17 16:20

I have a ListBox with an ItemsPanel


    
        
             

        
3条回答
  •  长情又很酷
    2020-12-17 16:40

    sorry I just noticed I forgot to save the edit...I realize you've already accepted an answer, but it seems more of a hack to me. Here's my implementation of FindChild, you might want to use it for the future or if you're going to be doing this often.

    public static T FindChild(this FrameworkElement obj, string name)
    {
        DependencyObject dep = obj as DependencyObject;
        T ret = default(T);
    
        if (dep != null)
        {
            int childcount = VisualTreeHelper.GetChildrenCount(dep);
            for (int i = 0; i < childcount; i++)
            {
                DependencyObject childDep = VisualTreeHelper.GetChild(dep, i);
                FrameworkElement child = childDep as FrameworkElement;
    
                if (child.GetType() == typeof(T) && child.Name == name)
                {
                    ret = (T)Convert.ChangeType(child, typeof(T));
                    break;
                }
    
                ret = child.FindChild(name);
                if (ret != null)
                    break;
            }
        }
        return ret;
    }
    

    It checks all the children and the children's children comparing the type and Name set on the control. Use it like this:

    StackPanel ipanel = ThumbListBox.FindChild("ThumbListStack");
    if(ipanel == null)
        MessageBox.Show("couldn't find anything");
    else
        MessageBox.Show("Aha! Found: " ipanel.Name);
    

提交回复
热议问题