以编程方式更改WPF可编辑ComboBox的背景颜色
我正在尝试在运行时使用代码动态更改可编辑的 ComboBox
的背景颜色。特别是,我想更改可编辑 TextBox
的背景,该文本框是 ComboBox
的一部分。
I'm trying to dynamically change the background color of an editable ComboBox
at runtime, using code. In particular, I want to change the background of the editable TextBox
that is part of the ComboBox
.
关于SO的答案有几个,就像这样:
There are several answers about this on SO, like this one:
但是,问题是它们都基于 XAML
并编辑默认模板。我不想这样做,我正在寻找一种只适用于代码的通用解决方案。
however, the problem is that they're all based on XAML
and editing default templates. I don't want to do that, I'm searching for a generic solution that works with just code.
有可能吗?我尝试了看似显而易见的解决方案:
Is it possible? I tried the solution that seems obvious:
TextBox textBox = (TextBox)comboBox.Template.FindName("PART_EditableTextBox", comboBox);
textBox.Background = Brushes.Yellow;
但这绝对没有作用。我缺少什么?
But this does absolutely nothing. What am I missing?
这是您可以做到的方式
<ComboBox Loaded="MyCombo_OnLoaded" x:Name="myCombo" IsEditable="True"></ComboBox>
private void MyCombo_OnLoaded(object sender, RoutedEventArgs e)
{
var textbox = (TextBox)myCombo.Template.FindName("PART_EditableTextBox", myCombo);
if (textbox!= null)
{
var parent = (Border)textbox.Parent;
parent.Background = Brushes.Yellow;
}
}