简体   繁体   中英

How do you access controls when using <TabItem.Header>, in code behind?

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.

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.

我不知道它是否有效,但你可以尝试一下:

(tabItem.Header as ContentControl).FindName("NAME_OF_TEXTBLOCK");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM