【问题标题】:Get UserControl inside tabItem在 tabItem 中获取 UserControl
【发布时间】:2017-11-09 20:32:04
【问题描述】:

我有一个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 时,它会返回一个项目。

我想获取包含在 contentTemplate DataTemplate 中的 UserControl MyUserControl

因为mUserControl在模板中,所以不能像mUserControl.doSomething()那样称呼它。

我尝试使用模板“FindName”功能:

ControlTemplate dt = tabs.Template;
MyUserControl mControl = (MyUserControl)dt.FindName("mUserControl", tabs);

但它返回 null。

我想访问MyUserControl 对象以调用将更改其状态的函数(显示控件并隐藏另一个控件)。 当用户单击 MenuItem(由 MainWindow 拥有)时会发生这种情况,但受影响的小部件是 UserControl。

那么,我如何获得对MyUserControl 对象的引用?

【问题讨论】:

  • 只是一个注释,但使用适当的 (MVVM) 设计你不应该想要这个。这太难了,因为你打破了模型/视图的分离。
  • 如何在不破坏模型/视图分离的情况下以适当的方式编写此内容?
  • 我同意这几乎肯定不是最好的方法。包括对您想要达到的结果的描述,我们或许可以提出更好的解决方案
  • 我更新了描述,希望更清楚

标签: c# wpf user-controls datatemplate tabitem


【解决方案1】:

您可以从 TabControl 更深入地遍历您的 Visual 树,并且可以获取其中的所有用户控件。

您应该阅读有关视觉树或这样的答案: Find control in the visual tree

【讨论】:

  • 谢谢,我会调查一下
  • 是的,这正是我要找的,非常感谢
猜你喜欢
  • 2017-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-26
相关资源
最近更新 更多