1

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 ?

Massimiliano Kraus
  • 3,638
  • 5
  • 27
  • 47
Artémis Young
  • 3,122
  • 1
  • 12
  • 17
  • 3
    Just a note but with a proper (MVVM) design you shouldn't want this. It is so difficult because you are breaking Model/View separation. – H H Jun 08 '17 at 08:29
  • How could I wrote this in a proper way wihtout breaking the Model/view separation ? – Artémis Young Jun 08 '17 at 08:30
  • I agree that this is almost certainly not the best approach. Include a description of the result you are trying to achieve and we may be able to suggest a better solution – Glen Thomas Jun 08 '17 at 08:32
  • I updated the description, hopefully it's clearer – Artémis Young Jun 08 '17 at 08:37

1 Answers1

1

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

Lukasz Cokot
  • 400
  • 2
  • 13