views:

73

answers:

1

How can I add tabs to a tabcontrol that exists in one usercontrol from another usercontrol that is contained within a tab itself?? Can I do it without passing in the tabcontrol as a parameter in the constructor, perhaps via some static global method?

I've tried

public static ObservableTabCollection FindCollectionFromUC(this DependencyObject depObject)
        {
            bool loop = true;
            var parent = (VisualTreeHelper.GetParent(depObject) as FrameworkElement);
            while (loop)
            {
                if (parent.GetType() is typeof(TabControl))
                {
                    loop = false;
                    return ((ObservableTabCollection)((TabControl)parent).ItemsSource);
                }
                parent = parent.GetParent() as FrameworkElement;
            }
            return null;
        }

==== EDIT ==== The Solution was this:

            bool loop = true;
            var parent = depObject as FrameworkElement;

            while (loop)
            {
                if (parent != null)
                {
                    parent = VisualTreeHelper.GetParent(parent) as FrameworkElement;
                    var type = parent.GetType();
                    if (parent.GetType() == typeof(TabControl))
                        {
                            loop = false;
                            return ((ObservableTabCollection)((TabControl)parent).ItemsSource);
                        }
                }
                else { loop = false; }
            }
            return null;
+1  A: 

The UserControl will need some means of finding the TabControl. You could pass an instance, as one option (probably the most robust). Alternatively, you could use some form of Dependency Injection or a service to retrieve the correct TabControl.

The other option, though potentially brittle, would be to navigate up the tree until you find a TabControl. FrameworkElement (of which UserControl and other panels derive) defines a Parent property. This would potentially allow you to walk up and find the TabControl instance containing this UserControl.

Reed Copsey
there is only one tabcontrol in the entire app, so it is the only one I need to find. Could you give an example of an implementation?
Jakob
Just recursively walk the "Parent" property until the object is a TabControl.
Reed Copsey
I'm not entirely sure how I'll do that correctly
Jakob
All i Find is a contentpresenter, but no tabcontrol
Jakob
Check the content presenter's parent, then it's parent, etc...
Reed Copsey
Sorry I explained that in a bad way - I checked it, but it goes this -UserControl -> TabItem -> TabPanel -> Grid -> Grid -> Grid -> null
Jakob
My problem was that I didn't actually use the VisualTreeHelper to crawl the VisualTree DependencyObject.Parent doesn't return the same as VisualTreeHelpe.GetParent(DependencyObject)
Jakob