如何自定义组合框内的复选框文本?

时间:2017-08-17 02:47:31

标签: c# wpf xaml

我注意到TextElement.Foreground不起作用,但Background = Red和FontWeight = Bold工作正常。知道为什么Foreground没有应用自定义样式吗?

<ComboBox.ItemTemplate>
    <DataTemplate>
        <StackPanel Orientation="Horizontal">
            <CheckBox Name="ChkDayResource" Style="{DynamicResource CheckBoxBlueStyle}"
                          IsChecked="{Binding Path=IsSelected}"
                          Tag="{Binding Path=., RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGridRow}, AncestorLevel=1}, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                          Click="ChkDayResource_Click" Content="{Binding Path=DayName}">
            </CheckBox>
            <!--<TextBlock Width="Auto" Text="{Binding Path=DayName}" IsHitTestVisible="True"/>-->
        </StackPanel>
    </DataTemplate>
</ComboBox.ItemTemplate>
<ComboBox.ItemContainerStyle>
    <Style TargetType="{x:Type ComboBoxItem}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ComboBoxItem}">
                    <Border x:Name="Bd"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="0"
                        Margin="-1,0,-1,0"
                        Background="{TemplateBinding Background}">
                        <StackPanel Orientation="Horizontal" Margin="10,0,10,0">
                            <ContentPresenter x:Name="content" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
                            VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                        </StackPanel>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsHighlighted" Value="True">
                            <Setter TargetName="Bd" Property="Background" Value="Red" />
                            <Setter Property="TextElement.Foreground" Value="Yellow" />
                            <Setter Property="TextElement.FontWeight" TargetName="content" Value="Bold" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ComboBox.ItemContainerStyle>

enter image description here

是否由于CheckBoxBlueStyle应用于CheckBox?如果是,我该如何覆盖样式?

1 个答案:

答案 0 :(得分:0)

默认CheckBox Style有错。例如在Blend中检查它显示:

<Style x:Key="CheckBoxStyle1" TargetType="{x:Type CheckBox}">
    <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
    <!-- other property setters -->
</Style>

因此,如果您不想使用默认值,则需要直接或通过样式分配新的Foreground

可能的解决方案:

<CheckBox Name="ChkDayResource" Foreground="{Binding Path=(TextElement.Foreground),RelativeSource={RelativeSource AncestorType=StackPanel}}"