在 tabItem 中获取 UserControl
Get UserControl inside tabItem
我有一个 TabControl
,有一个模板,像这样:
<TabControl ItemsSource="{Binding MyItems}" x:Name="tabs">
<TabControl.Resources>
<DataTemplate x:Key="contentTemplate" x:Name="contentTemplate" >
<other:MyUserControl x:Name="mUserControl" CustomData="{Binding}"/>
</DataTemplate>
<Style TargetType="{x:Type TabItem}">
<Setter Property="Header" Value="{Binding Name}" />
<Setter Property="ContentTemplate" Value="{StaticResource contentTemplate}"/>
</Style>
</TabControl.Resources>
</TabControl>
MyItems
是一个 ObservableCollection
自定义对象。
当我调用 tabs.SelectedContent
时,它 returns 一个项目。
我想要获取包含在 contentTemplate
DataTemplate 中的 UserControl MyUserControl
。
因为mUserControl
在模板中,所以我不能像mUserControl.doSomething()
那样调用它。
我尝试使用模板 "FindName" 函数:
ControlTemplate dt = tabs.Template;
MyUserControl mControl = (MyUserControl)dt.FindName("mUserControl", tabs);
但它 returns 无效。
我想访问 MyUserControl
对象以调用将更改其状态的函数(显示一个控件并隐藏另一个控件)。
当用户单击 MenuItem(由 MainWindow 拥有)但受影响的小部件是 UserControl 时,会发生这种情况。
那么,如何获取对 MyUserControl
对象的引用?
您可以从 TabControl 更深入地遍历您的可视化树,您可以获得其中的所有用户控件。
您应该阅读有关视觉树的内容或这样的答案:
Find control in the visual tree
我有一个 TabControl
,有一个模板,像这样:
<TabControl ItemsSource="{Binding MyItems}" x:Name="tabs">
<TabControl.Resources>
<DataTemplate x:Key="contentTemplate" x:Name="contentTemplate" >
<other:MyUserControl x:Name="mUserControl" CustomData="{Binding}"/>
</DataTemplate>
<Style TargetType="{x:Type TabItem}">
<Setter Property="Header" Value="{Binding Name}" />
<Setter Property="ContentTemplate" Value="{StaticResource contentTemplate}"/>
</Style>
</TabControl.Resources>
</TabControl>
MyItems
是一个 ObservableCollection
自定义对象。
当我调用 tabs.SelectedContent
时,它 returns 一个项目。
我想要获取包含在 contentTemplate
DataTemplate 中的 UserControl MyUserControl
。
因为mUserControl
在模板中,所以我不能像mUserControl.doSomething()
那样调用它。
我尝试使用模板 "FindName" 函数:
ControlTemplate dt = tabs.Template;
MyUserControl mControl = (MyUserControl)dt.FindName("mUserControl", tabs);
但它 returns 无效。
我想访问 MyUserControl
对象以调用将更改其状态的函数(显示一个控件并隐藏另一个控件)。
当用户单击 MenuItem(由 MainWindow 拥有)但受影响的小部件是 UserControl 时,会发生这种情况。
那么,如何获取对 MyUserControl
对象的引用?
您可以从 TabControl 更深入地遍历您的可视化树,您可以获得其中的所有用户控件。
您应该阅读有关视觉树的内容或这样的答案: Find control in the visual tree