如何为 WPF 应用程序设置默认字体? [英] How to set the default font for a WPF application?
问题描述
我希望能够为我的 WPF 应用程序定义一个字体系列.最好使用资源字典作为从 App.xaml
引用的主题.我尝试创建一个 Style
如下:
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>
但这行不通.将类型设置为 TextBlock
适用于大多数控件,但有一些控件不适用.
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.
有什么想法吗?
推荐答案
假设你的 Window
子类没有覆盖 DefaultStyleKey
,你可以简单地将它添加到你的 Window 样式,因为 TextElement.FontFamilyProperty
是一个继承的属性:
Assuming your Window
subclasses don't override DefaultStyleKey
, you can simply add it to your Window style, since TextElement.FontFamilyProperty
is an inherited property:
<Style TargetType="{x:Type Window}">
<Setter Property="FontFamily" Value="Segoe UI" />
</Style>
您还需要在 InitializeComponent
调用之后将以下内容添加到您的 App 构造函数中:
You also need to add the following to your App constructor after the InitializeComponent
call:
FrameworkElement.StyleProperty.OverrideMetadata(typeof(Window), new FrameworkPropertyMetadata
{
DefaultValue = FindResource(typeof(Window))
});
工作原理:App对象初始化完成后,其中指定的Window样式成为所有窗口的默认样式.
How it works: After the App object finishes initializing, the Window style specified therein is made the default style for all windows.
这篇关于如何为 WPF 应用程序设置默认字体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!