Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the background color of a WPF editable ComboBox programmatically

Tags:

c#

combobox

wpf

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.

There are several answers about this on SO, like this one:

WPF change the background color of an edittable combobox in code

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?

like image 395
Master_T Avatar asked Dec 08 '25 08:12

Master_T


1 Answers

This is how you can do it

<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;
       }
}
like image 116
Nitin Avatar answered Dec 09 '25 22:12

Nitin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!