从用户控件内部将选项卡添加到选项卡控件
如何从选项卡本身包含的另一个用户控件将选项卡添加到一个用户控件中存在的选项卡控件? 我可以在不将 tabcontrol 作为构造函数中的参数传递的情况下(也许通过某种静态全局方法)来完成此操作吗?
我已经尝试过
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;
}
====编辑==== 解决方案是这样的:
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;
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
UserControl 将需要一些方法来查找 TabControl。您可以传递一个实例,作为一种选择(可能是最强大的)。或者,您可以使用某种形式的依赖注入或服务来检索正确的 TabControl。
另一种选择虽然可能很脆弱,但可以在树中向上导航,直到找到 TabControl。 FrameworkElement(由 UserControl 和其他面板派生)定义了 父属性。这可能允许您找到包含此 UserControl 的 TabControl 实例。
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.