简体   繁体   English

如何更改包含TextBlock的ComboboxItem的选定项目的颜色?

[英]How to change the color of a selected item of a ComboboxItem which includes a TextBlock?

I have the following XAML of a Combobox: 我具有以下Combobox的XAML:

<ComboBox>
    <ComboBoxItem>
        <TextBlock FontWeight="Bold" Background="PaleGreen">1</TextBlock>
    </ComboBoxItem>
    <ComboBoxItem>
        <TextBlock FontWeight="Bold" Background="Salmon">2</TextBlock>
    </ComboBoxItem>
    <ComboBoxItem>
        <TextBlock FontWeight="Bold" Background="PaleTurquoise">3</TextBlock>
    </ComboBoxItem>
    <ComboBoxItem>
        <TextBlock FontWeight="Bold" Background="Gold">4</TextBlock>
    </ComboBoxItem>
    <ComboBoxItem>
        <TextBlock FontWeight="Bold" Background="Black" Foreground="White">5</TextBlock>
    </ComboBoxItem>
    <ComboBoxItem>
        <TextBlock FontWeight="Bold" Background="Gray">6</TextBlock>
    </ComboBoxItem>
</ComboBox>

The following pictures shows my problem: 下图显示了我的问题:

Combobox open 组合框打开

Combobox closed 组合框关闭

So you can see in the picture "Combobox closed" that the number "4" has no color, but I want that the text "4" is yellow. 因此,您可以在图片“关闭的组合框”中看到数字“ 4”没有颜色,但是我希望文本“ 4”为黄色。 Can you help me? 你能帮助我吗?

You need to edit the template of the ComboBox. 您需要编辑ComboBox的模板。

Go to [Document Outline], right-click the ComboBox, Edit Template->Edit a Copy. 转到[文档大纲],右键单击ComboBox,然后单击“编辑模板”->“编辑副本”。

Then find the "ComboBoxEditableTemplate" and edit the Border the contains the "PART_EditableTextBox". 然后找到“ ComboBoxEditableTemplate”并编辑包含“ PART_EditableTextBox”的边框。 Here's the specific part of the generated code:: 这是生成的代码的特定部分:

...
<ControlTemplate x:Key="ComboBoxEditableTemplate"
                 TargetType="{x:Type ComboBox}">
    <Grid x:Name="templateRoot"
          SnapsToDevicePixels="true">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="0"
                              MinWidth="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}" />
        </Grid.ColumnDefinitions>
        <Popup x:Name="PART_Popup"
               Grid.ColumnSpan="2"
               AllowsTransparency="true"
               IsOpen="{Binding IsDropDownOpen, RelativeSource={RelativeSource TemplatedParent}}"
               Placement="Bottom"
               PopupAnimation="{DynamicResource {x:Static SystemParameters.ComboBoxPopupAnimationKey}}">
            <Themes:SystemDropShadowChrome x:Name="shadow"
                                           MinWidth="{Binding ActualWidth, ElementName=templateRoot}"
                                           MaxHeight="{TemplateBinding MaxDropDownHeight}"
                                           Color="Transparent">
                <Border x:Name="dropDownBorder"
                        Background="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"
                        BorderBrush="{DynamicResource {x:Static SystemColors.WindowFrameBrushKey}}"
                        BorderThickness="1">
                    <ScrollViewer x:Name="DropDownScrollViewer">
                        <Grid x:Name="grid"
                              RenderOptions.ClearTypeHint="Enabled">
                            <Canvas x:Name="canvas"
                                    Width="0"
                                    Height="0"
                                    HorizontalAlignment="Left"
                                    VerticalAlignment="Top">
                                <Rectangle x:Name="opaqueRect"
                                           Width="{Binding ActualWidth, ElementName=dropDownBorder}"
                                           Height="{Binding ActualHeight, ElementName=dropDownBorder}"
                                           Fill="{Binding Background, ElementName=dropDownBorder}" />
                            </Canvas>
                            <ItemsPresenter x:Name="ItemsPresenter"
                                            KeyboardNavigation.DirectionalNavigation="Contained"
                                            SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
                        </Grid>
                    </ScrollViewer>
                </Border>
            </Themes:SystemDropShadowChrome>
        </Popup>
        <ToggleButton x:Name="toggleButton"
                      Grid.ColumnSpan="2"
                      Background="{TemplateBinding Background}"
                      BorderBrush="{TemplateBinding BorderBrush}"
                      BorderThickness="{TemplateBinding BorderThickness}"
                      IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
                      Style="{StaticResource ComboBoxToggleButton}" />
<!--  EDIT THIS PART LIKE SO  -->                     
        <Border x:Name="border"
                Margin="{TemplateBinding BorderThickness}"
                Background="{Binding SelectedItem.Background, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ComboBox}}, FallbackValue=Transparent}">
            <!--  Background="{StaticResource TextBox.Static.Background}">  -->
<!-- //////////////////////// -->
            <TextBox x:Name="PART_EditableTextBox"
                     Margin="{TemplateBinding Padding}"
                     HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
                     VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
                     IsReadOnly="{Binding IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
                     Style="{StaticResource ComboBoxEditableTextBox}" />
        </Border>
    </Grid>
    <ControlTemplate.Triggers>
        <Trigger Property="IsEnabled" Value="false">
            <Setter TargetName="border" Property="Opacity" Value="0.56" />
        </Trigger>
        <Trigger Property="IsKeyboardFocusWithin" Value="true">
            <Setter Property="Foreground" Value="Black" />
        </Trigger>
        <Trigger SourceName="PART_Popup" Property="HasDropShadow" Value="true">
            <Setter TargetName="shadow" Property="Margin" Value="0,0,5,5" />
            <Setter TargetName="shadow" Property="Color" Value="#71000000" />
        </Trigger>
        <Trigger Property="HasItems" Value="false">
            <Setter TargetName="dropDownBorder" Property="Height" Value="95" />
        </Trigger>
        <MultiTrigger>
            <MultiTrigger.Conditions>
                <Condition Property="IsGrouping" Value="true" />
                <Condition Property="VirtualizingPanel.IsVirtualizingWhenGrouping" Value="false" />
            </MultiTrigger.Conditions>
            <Setter Property="ScrollViewer.CanContentScroll" Value="false" />
        </MultiTrigger>
        <Trigger SourceName="DropDownScrollViewer" Property="ScrollViewer.CanContentScroll" Value="false">
            <Setter TargetName="opaqueRect" Property="Canvas.Top" Value="{Binding VerticalOffset, ElementName=DropDownScrollViewer}" />
            <Setter TargetName="opaqueRect" Property="Canvas.Left" Value="{Binding HorizontalOffset, ElementName=DropDownScrollViewer}" />
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>
...

After that, you can use it like the following, without using TextBlocks: 之后,您可以像下面那样使用它,而无需使用TextBlocks:

    <ComboBox IsEditable="True"
              Style="{DynamicResource YourComboBoxStyleName}">
        <ComboBoxItem Background="PaleGreen"
                      Content="1"
                      FontWeight="Bold" />
        <ComboBoxItem Background="Salmon"
                      Content="2"
                      FontWeight="Bold" />
        <ComboBoxItem Background="PaleTurquoise"
                      Content="3"
                      FontWeight="Bold" />
        <ComboBoxItem Background="Gold"
                      Content="4"
                      FontWeight="Bold" />
        <ComboBoxItem Background="Black"
                      Content="5"
                      FontWeight="Bold"
                      Foreground="White" />
        <ComboBoxItem Background="Gray"
                      Content="6"
                      FontWeight="Bold" />
    </ComboBox>

@janonimus: When I add a template as you said it has following code: @janonimus:当我添加一个模板时,如您所说,它具有以下代码:

<Window.Resources>
    <ControlTemplate x:Key="ComboBoxControlTemplate1" TargetType="{x:Type ComboBox}">
        <Grid x:Name="Placement" SnapsToDevicePixels="True">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>
            <Popup x:Name="PART_Popup" AllowsTransparency="True" Grid.ColumnSpan="2" IsOpen="{Binding IsDropDownOpen, RelativeSource={RelativeSource TemplatedParent}}" PopupAnimation="{DynamicResource {x:Static SystemParameters.ComboBoxPopupAnimationKey}}" Placement="Bottom">
                <Themes:SystemDropShadowChrome x:Name="Shdw" Color="Transparent" MaxHeight="{TemplateBinding MaxDropDownHeight}" MinWidth="{Binding ActualWidth, ElementName=Placement}">
                    <Border x:Name="DropDownBorder" BorderBrush="{DynamicResource {x:Static SystemColors.WindowFrameBrushKey}}" BorderThickness="1" Background="{DynamicResource {x:Static SystemColors.WindowBrushKey}}">
                        <ScrollViewer x:Name="DropDownScrollViewer">
                            <Grid RenderOptions.ClearTypeHint="Enabled">
                                <Canvas HorizontalAlignment="Left" Height="0" VerticalAlignment="Top" Width="0">
                                    <Rectangle x:Name="OpaqueRect" Fill="{Binding Background, ElementName=DropDownBorder}" Height="{Binding ActualHeight, ElementName=DropDownBorder}" Width="{Binding ActualWidth, ElementName=DropDownBorder}"/>
                                </Canvas>
                                <ItemsPresenter x:Name="ItemsPresenter" KeyboardNavigation.DirectionalNavigation="Contained" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                            </Grid>
                        </ScrollViewer>
                    </Border>
                </Themes:SystemDropShadowChrome>
            </Popup>
            <Themes:ListBoxChrome x:Name="Border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Grid.ColumnSpan="2" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderFocused="{TemplateBinding IsKeyboardFocusWithin}"/>
            <TextBox x:Name="PART_EditableTextBox" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" IsReadOnly="{Binding IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}" Margin="{TemplateBinding Padding}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}">
                <TextBox.Style>
                    <Style TargetType="{x:Type TextBox}">
                        <Setter Property="OverridesDefaultStyle" Value="True"/>
                        <Setter Property="AllowDrop" Value="True"/>
                        <Setter Property="MinWidth" Value="0"/>
                        <Setter Property="MinHeight" Value="0"/>
                        <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
                        <Setter Property="ScrollViewer.PanningMode" Value="VerticalFirst"/>
                        <Setter Property="Stylus.IsFlicksEnabled" Value="False"/>
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="{x:Type TextBox}">
                                    <ScrollViewer x:Name="PART_ContentHost" Background="Transparent" Focusable="False" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"/>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </TextBox.Style>
            </TextBox>
            <ToggleButton Grid.Column="1" IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}">
                <ToggleButton.Style>
                    <Style TargetType="{x:Type ToggleButton}">
                        <Setter Property="OverridesDefaultStyle" Value="True"/>
                        <Setter Property="IsTabStop" Value="False"/>
                        <Setter Property="Focusable" Value="False"/>
                        <Setter Property="ClickMode" Value="Press"/>
                        <Setter Property="Background" Value="Transparent"/>
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="{x:Type ToggleButton}">
                                    <Themes:ButtonChrome x:Name="Chrome" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderPressed="{TemplateBinding IsPressed}" RoundCorners="False" SnapsToDevicePixels="True" Width="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}">
                                        <Path x:Name="Arrow" Data="M0,0L3.5,4 7,0z" Fill="Black" HorizontalAlignment="Center" Margin="0,1,0,0" VerticalAlignment="Center"/>
                                    </Themes:ButtonChrome>
                                    <ControlTemplate.Triggers>
                                        <Trigger Property="IsChecked" Value="True">
                                            <Setter Property="RenderPressed" TargetName="Chrome" Value="True"/>
                                        </Trigger>
                                        <Trigger Property="IsEnabled" Value="False">
                                            <Setter Property="Fill" TargetName="Arrow" Value="#FFAFAFAF"/>
                                        </Trigger>
                                    </ControlTemplate.Triggers>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </ToggleButton.Style>
            </ToggleButton>
        </Grid>
        <ControlTemplate.Triggers>
            <Trigger Property="IsKeyboardFocusWithin" Value="True">
                <Setter Property="Foreground" Value="Black"/>
            </Trigger>
            <Trigger Property="IsDropDownOpen" Value="True">
                <Setter Property="RenderFocused" TargetName="Border" Value="True"/>
            </Trigger>
            <Trigger Property="HasItems" Value="False">
                <Setter Property="Height" TargetName="DropDownBorder" Value="95"/>
            </Trigger>
            <Trigger Property="IsEnabled" Value="False">
                <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                <Setter Property="Background" Value="#FFF4F4F4"/>
            </Trigger>
            <MultiTrigger>
                <MultiTrigger.Conditions>
                    <Condition Property="IsGrouping" Value="True"/>
                    <Condition>
                        <Condition.Value>
                            <System:Boolean>False</System:Boolean>
                        </Condition.Value>
                    </Condition>
                </MultiTrigger.Conditions>
                <Setter Property="ScrollViewer.CanContentScroll" Value="False"/>
            </MultiTrigger>
            <Trigger Property="HasDropShadow" SourceName="PART_Popup" Value="True">
                <Setter Property="Margin" TargetName="Shdw" Value="0,0,5,5"/>
                <Setter Property="Color" TargetName="Shdw" Value="#71000000"/>
            </Trigger>
            <Trigger Property="CanContentScroll" SourceName="DropDownScrollViewer" Value="False">
                <Setter Property="Canvas.Top" TargetName="OpaqueRect" Value="{Binding VerticalOffset, ElementName=DropDownScrollViewer}"/>
                <Setter Property="Canvas.Left" TargetName="OpaqueRect" Value="{Binding HorizontalOffset, ElementName=DropDownScrollViewer}"/>
            </Trigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>
</Window.Resources>

In addition, an error is thrown as soon as I have inserted the template: 此外,一旦插入模板,就会引发错误:

InvalidOperationException: Nicht-NULL-Wert für "Property" erforderlich. InvalidOperationException:Nicht-NULL-Wert“属性” erforderlich。

EDIT: 编辑:

I have the solution. 我有解决方案。 It was quite easy :DI don't need a template. 这很简单:DI不需要模板。 I just added triggers: 我刚刚添加了触发器:

                <Style TargetType="ComboBox">
                    <Setter Property="Background" Value="Transparent"/>
                    <Setter Property="FontSize" Value="10"/>
                    <Setter Property="HorizontalAlignment" Value="Center"/>
                    <Setter Property="VerticalAlignment" Value="Center"/>
                    <Setter Property="Width" Value="115"/>
                    <Setter Property="Foreground" Value="Black"/>
                    <Setter Property="BorderBrush" Value="White"/>
                    <Setter Property="SelectedIndex" Value="0"/>
                    <Setter Property="HorizontalContentAlignment" Value="Center"/>
                    <Setter Property="IsEditable" Value="True"/>
                    <EventSetter Event="SelectionChanged" Handler="SelectionChanged"/>
                    <Style.Triggers>
                        <Trigger Property="IsEnabled" Value="False">
                            <Setter Property="Opacity" Value="0.4"/>
                        </Trigger>
                        <Trigger Property="SelectedIndex" Value="0">
                            <Setter Property="Background" Value="PaleGreen"/>
                            <Setter Property="Foreground" Value="Black"/>
                        </Trigger>
                        <Trigger Property="SelectedIndex" Value="1">
                            <Setter Property="Background" Value="Salmon"/>
                            <Setter Property="Foreground" Value="Black"/>
                        </Trigger>
                        <Trigger Property="SelectedIndex" Value="2">
                            <Setter Property="Background" Value="PaleTurquoise"/>
                            <Setter Property="Foreground" Value="Black"/>
                        </Trigger>
                        <Trigger Property="SelectedIndex" Value="3">
                            <Setter Property="Background" Value="Gold"/>
                            <Setter Property="Foreground" Value="Black"/>
                        </Trigger>
                        <Trigger Property="SelectedIndex" Value="4">
                            <Setter Property="Background" Value="Black"/>
                            <Setter Property="Foreground" Value="White"/>
                        </Trigger>
                        <Trigger Property="SelectedIndex" Value="5">
                            <Setter Property="Background" Value="Gray"/>
                            <Setter Property="Foreground" Value="Black"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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