3

I have a combobox:

var cmbLogin = new ComboBox()
{
    Width = 200,
    Height = 50,
    Margin = new Thickness(20),
    HorizontalContentAlignment = HorizontalAlignment.Center,
    Background = Brushes.Transparent,
    Foreground = Brushes.White,
    Focusable = true,
};

cmbLogin.Items.Add("AAAAA");
cmbLogin.Items.Add("BBBBB");

Now I want to define style and triggers:

Style cmbStyle = new Style(typeof(ComboBox));
cmbStyle.Setters.Add(new Setter(BackgroundProperty, Brushes.Green));
cmbStyle.Setters.Add(new Setter(ForegroundProperty, Brushes.Red));


Trigger t1 = new Trigger { Property = ComboBox.IsMouseOverProperty, Value = true };
t1.Setters.Add( new Setter(ComboBox.BackgroundProperty, Brushes.Yellow));
cmbStyle.Triggers.Add(t1);
cmbLogin.Style = cmbStyle;

but the effect with and without mouse is always the same as before

enter image description here enter image description here

thanx

Luca
  • 918
  • 2
  • 13
  • 30
  • You're defining your custom `Style` but using it in connection with the default `ControlTemplate`. `Triggers` and `Setters` work correctly relative to the control template. Either you also define your own custom `ControlTemplate` or adhere to the default one. You can't have it both ways. – jsanalytics Jan 20 '17 at 13:42
  • 1
    Why not use XAML? 100x easier! – Markinson Jan 20 '17 at 14:02
  • Also, i assume you know you should be doing it in XAML, but you **want** to do it in code-behind. Which makes me think of the proverbial _"bringing a knife to a gun fight"_. Can you do it? Of course you can ! But don't complain later if you get badly hurt...:O) – jsanalytics Jan 20 '17 at 14:05
  • I have to build plugins dll with the appdomain tecnique. so no xaml but everything runtime built by reading runtime properties coming from a xml file. This is the reason. – Luca Jan 20 '17 at 14:29
  • Uh is that a fight? Seemed just a little quarrel.... – Luca Jan 20 '17 at 14:34
  • Do you use Win8 or higher? Check out [this question](http://stackoverflow.com/questions/16183746/combobox-background-not-being-applied-in-windows-8) (possible duplicate). – icebat Jan 20 '17 at 15:38
  • Yes I already saw this solution but in my case -as I said- I am forced to use code behind ONLY and I can't figure out how to translate it – Luca Jan 20 '17 at 17:08

1 Answers1

3

It seems to me that your issue is not the Code-Behind approach, rather the usage of the wrong Property. Your Desired/Expected UI would not have happen even if you would use XAML.

ComboBox Background property is not the property you need.

Just to make the first point clear: If you would have tried to change the foreground instead of Background it would have worked well and change the text foreground.

But unfortunately to change your ComboBox Background or Highlight you need to work a bit harder. And here is a good explanation: Change-background-of-WPF-Combobox customizing-wpf-combo-box-style

Hope it helps

Oran Gerbovski
  • 319
  • 3
  • 7