如何设置WPF应用程序的默认字体?
我希望能够为我的 WPF 应用程序定义字体系列。最好使用资源字典作为从 App.xaml 引用的主题。我尝试创建一个 Style
如下:
<Style TargetType="{x:Type Control}">
<Setter Property="FontFamily" Value="Segoe UI" />
</Style>
但这不起作用。将类型设置为 TextBlock
适用于大多数控件,但有一些控件不适用。
我知道您可以在窗口上设置字体,并让该窗口的所有子控件继承该字体。但我认为任何对话框窗口都会恢复为默认字体,这并不完全是我想要的。
有什么想法吗?
I want to be able to define a font family for my WPF application. Preferably using a resource dictionary as a theme referenced from App.xaml
. I've tried creating a Style
as follows:
<Style TargetType="{x:Type Control}">
<Setter Property="FontFamily" Value="Segoe UI" />
</Style>
But this doesn't work. Setting the type to TextBlock
works for most controls but there are a few controls where this doesn't apply.
I know you can set the font on a window and have all child controls of that window inherit the font. But I think any dialog windows will go back to the default font, which is not exactly what I want.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
假设您的
Window
子类不重写DefaultStyleKey
,您只需将其添加到您的 Window 样式中,因为TextElement.FontFamilyProperty
是继承的属性:您还需要在
InitializeComponent
调用之后将以下内容添加到 App 构造函数中:工作原理:App 对象完成初始化后,其中指定的 Window 样式将成为所有窗口的默认样式。
Assuming your
Window
subclasses don't overrideDefaultStyleKey
, you can simply add it to your Window style, sinceTextElement.FontFamilyProperty
is an inherited property:You also need to add the following to your App constructor after the
InitializeComponent
call:How it works: After the App object finishes initializing, the Window style specified therein is made the default style for all windows.
大多数建议的解决方案对我来说不起作用。我的简单解决方案:
将其添加到 App.xaml:
将其添加到 MainWindow 构造函数中(在 InitializeComponent 之后):
Most of proposed solutions didn't work for me. My simple solution:
Add this to App.xaml:
Add this in your MainWindow constructor (after InitializeComponent):
实际上,您可以结合此处的一些其他答案获得完整的 XAML 解决方案。
如果您的主窗口名为
WinMain
(您在所有其他窗口之前加载的窗口),只需添加一个引用名为WinAll
的样式,然后以这种方式定义您的样式
Actually you can get a full XAML solution combining some of the other answers here.
If your main window is called
WinMain
(the one you load before all others), just add a reference to a style named e.g.WinAll
and then define your style this way
以编程方式执行此操作的一种简单方法:
One simple way to do it programmatically:
我发现了这个:
I found this :
在
App.xaml
中尝试这个简单的解决方法(不需要隐藏代码):只需将您的 Windows 样式绑定到此即可。非常适合我。只需要在嵌套树中定义一些属性。例如,属性
FontSize
只能在通用部分中指定。我不知道为什么需要做这个技巧。这很奇怪,因为 Label 应该派生自 Control。有人对此有任何想法吗?
Try this simple workaround in the
App.xaml
(no code behind needed):Just bind your windows style to this. Works perfectly for me. Only some properties need to be defined in the nested tree. For example the property
FontSize
can be specify only in the generic section.I don't know why is necessary to do this trick. It's strange because Label should be derived from Control. Anyone have any idea about it?