简体   繁体   English

从usercontrol内部向tabcontrol添加选项卡

[英]adding tabs to tabcontrol from inside usercontrol

How can I add tabs to a tabcontrol that exists in one usercontrol from another usercontrol that is contained within a tab itself?? 如何将标签添加到tabcontrol中,该tabcontrol存在于一个用户控件中,该控件位于选项卡本身中? Can I do it without passing in the tabcontrol as a parameter in the constructor, perhaps via some static global method? 我可以在不将tabcontrol传递给构造函数中的参数的情况下执行此操作,可能通过一些静态全局方法吗?

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;

The UserControl will need some means of finding the TabControl. UserControl需要一些方法来查找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. 或者,您可以使用某种形式的依赖注入或服务来检索正确的TabControl。

The other option, though potentially brittle, would be to navigate up the tree until you find a TabControl. 另一种选择,虽然可能很脆弱,但是可以向上导航树,直到找到TabControl。 FrameworkElement (of which UserControl and other panels derive) defines a Parent property. FrameworkElement(UserControl和其他面板派生的)定义Parent属性。 This would potentially allow you to walk up and find the TabControl instance containing this UserControl. 这可能允许您向上走,找到包含此UserControl的TabControl实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM