Search code examples
c#wpfuser-controlsdatatemplatetabitem

Get UserControl inside tabItem


I have a TabControl, with a template, like so :

<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 is an ObservableCollection of custom objects. When I call tabs.SelectedContent it returns an item.

I would like to get the UserControl MyUserControl contained in the contentTemplate DataTemplate.

Because mUserControl is in a template, I can't call it like mUserControl.doSomething().

I tried to use the templates "FindName" function :

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

But it returns null.

I would like to access the MyUserControl object to call a function that will change it's state (show a control and hide another one). This happens when the user clicks on a MenuItem (owned by the MainWindow), but the affected widget is the UserControl.

So, how do I get a reference to the MyUserControl object ?


Solution

  • You can traverse your Visual tree from your TabControl deeper inside and you can get all your user controls which are inside it.

    You should read about visual tree or answers like this: Find control in the visual tree