Question

Going off this sample from the MSDN under TabControl:

<TabControl>
    <TabItem>
    <TabItem.Header>
      <StackPanel Orientation="Horizontal">
        <Ellipse Width="10" Height="10" Fill="DarkGray"/>
        <TextBlock>Tab 1</TextBlock>
      </StackPanel>
    </TabItem.Header>
    <StackPanel>
      <TextBlock>Enter some text</TextBlock>
      <TextBox Name="textBox1" Width="50"/>
    </StackPanel>
  </TabItem>
  <TabItem Header="Tab 2">
    <!--Bind TextBlock.Text to the TextBox on the first
    TabItem.-->
    <TextBlock Text="{Binding ElementName=textBox1, Path=Text}"/>
  </TabItem>
</TabControl>

How do you access the stackpanel (and it's children) that is inside the <TabItem.Header> tag from C# code behind? When I try to use .Header intellisense treats it as if the header was defined the way the 2nd tab above is.

Was it helpful?

Solution

I agree with HighCore. You should be using databinding instead of trying to manipulate the UI elements directly. In the off chance that you want to stick with your current plan, here's how:

<TabControl>
    <TabItem>
    <TabItem.Header>
      <StackPanel Name="tab1StackPanel" Orientation="Horizontal">
        ...
      </StackPanel>
    </TabItem.Header>        
  </TabItem>
  <TabItem Header="Tab 2">
    ...
  </TabItem>
</TabControl>

Now, from code behind you can reference tab1StackPanel directly, as defining a Name exposes it to codebehind WPF (as long as it's not inside a template).

You could also use the VisualTreeHelper to find visual children of the first tab...

BUT... once again, you should probably be using databinding, so I'd make sure you're following a good pattern before going too much further.

OTHER TIPS

I don't know if it works but you can give it a try:

(tabItem.Header as ContentControl).FindName("NAME_OF_TEXTBLOCK");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top