views:

1317

answers:

2

I am trying to create a WPF control at runtime, but I can't figure out how to make it ignore the styles coming from the App.xml resources. I've tried setting the style to null and the OverridesDefaultStyle to true but no luck. The app settings set the foreground to white, and I can't seem to explicity set it to anything else.

        Label tb = new Label();
        tb.OverridesDefaultStyle = true;
        tb.Style = null;
        tb.Foreground = new SolidColorBrush(Colors.Black);
        this.Children.Add(tb);

Edit: For some reason I never could get the Label to work but when I switched to the textbox, it worked fine.

Thank you for your responses.

+1  A: 

The following near-identical code works for me:

  Label l = new Label();
  l.Content = "Fie!!!";
  l.Style = null;
  l.OverridesDefaultStyle = true;  // not required, see below
  l.Foreground = new SolidColorBrush(Colors.Blue);
  ((Grid)Content).Children.Add(l);

From experimenting, however, it seems that if you set OverridesDefaultStyle = true after setting Style, it works okay. But if you set OverridesDefaultStyle before setting Style, it all goes wrong. (No, I don't know why this happens! grin) So move the OverridesDefaultStyle setter to after the Style setter, or (since it's not required for the effect you want), just remove it.

itowlson
+1  A: 

All you have to do is set Style to null to stop it from inheriting. Then you can set the Foreground to whatever you like:

var tb = new TextBlock() { Text = "Hello" };
tb.Style = null;
tb.Foreground = Brushes.Blue;
this.Children.Add(tb);

If this isn't working for you, I'd suggest something else entirely is going on.

HTH, Kent

PS. Use Brushes.Black rather than creating your own SolidColorBrush. Not only is it cleaner, the brush will also be frozen. Your code creates an unfrozen brush, which is less efficient. You can also freeze it yourself by calling Freeze() on the brush.

Kent Boogaart
I didn't know about the freezing of brushes, thanks for that. It has to be from a user defined color, so new SolidColorBrush(inputColor) and then brush.Freeze() is what I have.
Alan Jackson