WPF在代码中更改可编辑组合框的背景颜色

时间:2015-08-21 19:17:33

标签: c# wpf combobox

我需要在代码中设置可编辑combobox的背景颜色。这就是我所拥有的,但不会改变颜色:

        ComboBox comboBox = sender as ComboBox;
        comboBox.Background = Brushes.PeachPuff;

        if (comboBox.IsEditable == true)
        {
            TextBox textBox = (TextBox)comboBox.Template.FindName("PART_EditableTextBox", comboBox);
            if (textBox != null)
            {
                textBox.Background = Brushes.PeachPuff;

            }
        }

我期待背景颜色变为PeachPuff(浅橙色),但没有任何反应 - 任何想法?

1 个答案:

答案 0 :(得分:2)

使用Date()属性更改combobox的{​​{1}}仅用于Win7及更早版本,在Windows 8及更高版本中background的默认模板已更改,以修复您应编辑默认模板

  1. 使用 VisualStudio 2013 混合,右键单击background并选择EditTemplate>编辑副本:
  2. Edit a Copy

    1. 在生成的Xaml搜索ComboBox并将combobox标记替换为<ControlTemplate TargetType="{x:Type ToggleButton}">{StaticResource ComboBox.Static.Background}属性后,您的代码应如下所示更新:

      TemplateBinding
    2. 现在,您可以使用Background属性更改Background颜色:

       ...
        <Setter Property="Template">
              <Setter.Value>
                  <ControlTemplate TargetType="{x:Type ToggleButton}">
                      <Border x:Name="templateRoot" BorderBrush="{StaticResource ComboBox.Static.Border}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
                          <Border x:Name="splitBorder" BorderBrush="Transparent" BorderThickness="1" HorizontalAlignment="Right" Margin="0" SnapsToDevicePixels="true" Width="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}">
                              <Path x:Name="arrow" Data="F1 M 0,0 L 2.667,2.66665 L 5.3334,0 L 5.3334,-1.78168 L 2.6667,0.88501 L0,-1.78168 L0,0 Z" Fill="{StaticResource ComboBox.Static.Glyph}" HorizontalAlignment="Center" Margin="0" VerticalAlignment="Center"/>
                          </Border>
                      </Border>
                      <ControlTemplate.Triggers>
                          <MultiDataTrigger>
                           ...
      

      combobox