WPF Nested Styles

孤街浪徒 提交于 2019-12-10 18:19:41

问题


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.


回答1:


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>



回答2:


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>


来源:https://stackoverflow.com/questions/13858288/wpf-nested-styles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!