问题描述
我需要在代码中设置可编辑的 combobox
的背景颜色.这是我所拥有的,但不会改变颜色:
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;
}
}
我原以为背景颜色会更改为 PeachPuff(浅橙色),但没有任何反应 - 有什么想法吗?
I was expecting the background color to change to PeachPuff (light orange) but nothing happens - any ideas?
推荐答案
使用 background
属性更改 combobox
的 background
仅使用要在 Win7 及更早版本中工作,在 Windows 8 及更高版本中,ComboBox
的默认模板已更改,以修复您应该编辑默认模板的问题,
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,
- 使用 VisualStudio 2013 或 Blend,右键单击
combobox
并选择 EditTemplate > Edit a Copy:
- using VisualStudio 2013 or Blend, Right Click the
combobox
and choose EditTemplate > Edit a Copy :
在生成的 Xaml 中搜索
并替换
{StaticResource ComboBox.Static.Background}
code> 将TemplateBinding
标记为Background
属性,更新后您的代码应如下所示:
In the generated Xaml search for
<ControlTemplate TargetType="{x:Type ToggleButton}">
and replace the{StaticResource ComboBox.Static.Background}
markup with aTemplateBinding
to theBackground
property, 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>
...
现在,您可以使用 Background 属性来更改 Combobox
颜色:
<Grid>
<ComboBox IsEditable="True" x:Name="EditableComboBox" Background="PeachPuff" VerticalAlignment="Center" HorizontalAlignment="Center" Width="200" Style="{DynamicResource ComboBoxStyle1}" >
</ComboBox>
</Grid>
这篇关于WPF 在代码中更改可编辑组合框的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!