Sinatr
Sinatr

Reputation: 22008

Property inheritance through TabControl

I have window, where I set some property

<Window Foreground="White" ...

Now all my children get that property inherited, right? Like this

<Window>
    <Grid>
        <Label> <-- has Foreground="White" without need to explicitly specify it -->
        ...

However, once I use TabControl, inheritance is broken.

<Window>
    <Grid>
        <TabControl>
            <TabItem>
                <Grid>
                    <Label> <-- doesn't inherit Foreground property from Window -->

I can't set Foreground for TabControl, perhaps this is the reason. Question is why and what to do? I can use styles, but is there other, more obvious and less code-ish way?

Upvotes: 2

Views: 317

Answers (2)

user128300
user128300

Reputation:

The reason why inheritance has no effect here is dependency property value precedence. Inherited values have almost the lowest precedence; they will be overriden by the default style for the label (which assigns a black value to the foreground color).

In your second code snippet, you write that the Label inside the Grid has white foreground; this is probably because you have applied a style to that label, or because your operating system's default foreground color is white. In any case, this Label definitely does not inherit its white color from the window, if it is an unstyled Label control.

Therefore, you have to add a style to your Window.

<Window.Resources>
    <Style TargetType="Label">
        <Setter Property="Foreground" Value="White"/>
    </Style>
</Window.Resources>

Upvotes: 1

Sheridan
Sheridan

Reputation: 69987

There's really not much that you can do in this case. The property value inheritance is definitely stopping at the TabControl. I suspect that it has something to do with all of the different Templates and Styles that the TabItem provides (although that shouldn't cause any problem really).

As you said, the only way to set the Foreground properties of multiple controls inside the TabControl is to use a Style. However, there is a way to set the Foreground property on controls that don't have their own Foreground property. That is to use the TextElement.Foreground Attached Property:

<Grid TextElement.Foreground="Red">
    <StackPanel>
        <TextBlock Text="Hey what colour am I?" />
        <TabControl>
            <TabItem Header="Header" TextElement.Foreground="Red" />
        </TabControl>
    </StackPanel>
</Grid>

Of course, the TabItem control does have a Foreground property, so this is not a great example... it works better on a Grid full of TextBlocks. You should note though, that setting TextElement.Foreground Attached Property will not have any effect on a control that has no TextElement in it. (TextBlock controls contain TextElements). You can also call TextBlock.Foreground.

Upvotes: 2

Related Questions