Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Nested Styles

I have TextBlocks and Comboboxes in my application i want the Textblock foreground to be white and the Combobox Foreground to be Black.

What i tried was:

    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<Style TargetType="{x:Type TextBlock}">
    <Setter Property="Foreground" Value="White" />
</Style>
<Style TargetType="{x:Type ComboBox}">
    <Setter Property="Foreground" Value="Red" />
</Style>
</ResourceDictionary>



<Grid Background="Black">
    <TextBlock Height="23" HorizontalAlignment="Left" Margin="27,30,0,0" Name="textBlock1" Text="TextBlock" VerticalAlignment="Top" />
    <ComboBox Height="23" HorizontalAlignment="Left" Margin="12,99,0,0" Name="comboBox1" VerticalAlignment="Top" Width="120" />
</Grid>

But the combobox Foreground is still white how to override the TextBlock Foreground in the combobox? (In CSS this is easy but no idea in WPF)

If i remove the Style for TextBlock everything else changes just fine but when i put the style back every foreground is white.

like image 469
Sam_vdd Avatar asked Dec 13 '12 10:12

Sam_vdd


2 Answers

To nest styles, you can include them in the resources of parent. You could also change the TextBlock.Foreground property of Combobox style

<Style TargetType="{x:Type ComboBox}">
    <Style.Resources>
        <Style TargetType="{x:Type TextBlock}">
            <Setter Property="Foreground" Value="Black" />
        </Style>
    </Style.Resources>
    <Setter Property="Foreground" Value="Black" />
    <Setter Property="textBlock.Foreground" Value="Black" />
</Style>
like image 109
Kek Avatar answered Nov 20 '22 16:11

Kek


Try setting the style for ComboBoxItem

<Style TargetType="{x:Type TextBlock}">
    <Setter Property="Foreground" Value="White"/>
    <Setter Property="Background" Value="Black"/>
</Style>
<Style TargetType="{x:Type ComboBoxItem}">
    <Setter Property="Foreground" Value="White"/>
    <Setter Property="Background" Value="Black"/>
</Style>
<Style TargetType="{x:Type ComboBox}">
    <Setter Property="Foreground" Value="White"/>
    <Setter Property="Background" Value="Black"/>
</Style>
like image 45
Johan Larsson Avatar answered Nov 20 '22 16:11

Johan Larsson