ComboBox的样式背景颜色匹配所选项目背景颜色

时间:2014-01-16 16:54:33

标签: wpf xaml combobox

我有一个组合框,其中的项目具有不同的背景颜色。当我选择彩色项目时,组合框的背景仍然是默认颜色。如何根据所选项目的背景颜色绑定组合框的背景?

    <ComboBox.Style>
       <Style TargetType="ComboBox">
         <Style.Setters>
           <Setter Property="Background" Value="????"/>
         </Style.Setters>
       </Style>
   </ComboBox.Style>
   <ComboBox.ItemContainerStyle>
     <Style TargetType="ComboBoxItem">
       <Style.Setters>
         <Setter Property="Background" Value="{Binding Path=Color}"/>
       </Style.Setters>
     </Style>
   </ComboBox.ItemContainerStyle>

1 个答案:

答案 0 :(得分:1)

试试这个......如果我的要求不合适的话。

    <ComboBox Height="25" Width="200" >         
        <ComboBox.ItemContainerStyle>
            <Style TargetType="ComboBoxItem">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="ComboBoxItem">
                            <Border x:Name="Border" Background="{TemplateBinding Background }">
                                <TextBlock FontSize="25" FontFamily="Segoe UI Light">
                                            <ContentPresenter></ContentPresenter>
                                </TextBlock>
                            </Border>
                            <ControlTemplate.Triggers>
                                <Trigger Property="ComboBoxItem.IsSelected" Value="True">
                                    <Setter TargetName="Border" Property="Background" Value="{Binding Path=Background, RelativeSource={RelativeSource TemplatedParent}}"></Setter>
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </ComboBox.ItemContainerStyle>
        <ComboBoxItem Height="30" Background="Red">czczczc</ComboBoxItem>
        <ComboBoxItem Height="30"  Background="Green">czczczc</ComboBoxItem>
        <ComboBoxItem Height="30"  Background="Blue">czczczc</ComboBoxItem>
    </ComboBox>

如果你想改变组合框下拉,你可以像这样定义它的背景

 Background="{Binding RelativeSource={RelativeSource Self}, Path=SelectedItem.Background}"