问题
I need to set the background color of an editable combobox in code. This is what I have but does not change the color:
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;
}
}
I was expecting the background color to change to PeachPuff (light orange) but nothing happens - any ideas?
回答1:
Changing the combobox's background using the background property only use to work in Win7 and older, in windows 8 and above the default template for the ComboBox has been changed, to fix that you should edit the default template,
- using VisualStudio 2013 or Blend, Right Click the
comboboxand choose EditTemplate > Edit a Copy :
In the generated Xaml search for
<ControlTemplate TargetType="{x:Type ToggleButton}">and replace the{StaticResource ComboBox.Static.Background}markup with aTemplateBindingto theBackgroundproperty, your code should look like this after the update :... <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> ...Now, you can use the Background property to change the
Comboboxcolor:<Grid> <ComboBox IsEditable="True" x:Name="EditableComboBox" Background="PeachPuff" VerticalAlignment="Center" HorizontalAlignment="Center" Width="200" Style="{DynamicResource ComboBoxStyle1}" > </ComboBox> </Grid>
来源:https://stackoverflow.com/questions/32147838/wpf-change-the-background-color-of-an-edittable-combobox-in-code