How to override application styles in a wpf control created at runtime

半腔热情 提交于 2019-12-11 16:55:45

问题


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:


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.

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.




回答2:


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.



来源:https://stackoverflow.com/questions/788203/how-to-override-application-styles-in-a-wpf-control-created-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!