如何在运行时创建的 wpf 控件中覆盖应用程序样式 [英] How to override application styles in a wpf control created at runtime

查看:33
本文介绍了如何在运行时创建的 wpf 控件中覆盖应用程序样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在运行时创建 WPF 控件,但我不知道如何让它忽略来自 App.xml 资源的样式.我试过将样式设置为 null 并将 OverridesDefaultStyle 设置为 true 但没有运气.应用设置将前景设置为白色,我似乎无法将其明确设置为其他任何内容.

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);

由于某种原因,我无法让标签工作,但是当我切换到文本框时,它工作正常.

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

感谢您的回复.

推荐答案

您所要做的就是将 Style 设置为 null 以阻止它继承.然后您可以将 Foreground 设置为您喜欢的任何内容:

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.

附注.使用 Brushes.Black 而不是创建自己的 SolidColorBrush.不仅干净,刷子也会结冰.您的代码创建了一个未冻结的画笔,效率较低.您也可以通过在画笔上调用 Freeze() 自行冻结它.

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.

这篇关于如何在运行时创建的 wpf 控件中覆盖应用程序样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆