设置全局字体系列
可能的重复:
如何设置 wpf 应用程序的默认字体?
具有 Web 开发背景的我经常对如何为控件分配样式感到困惑.我想做的是为整个应用程序设置一个全局字体系列.
Coming from a web development background I often get mixed up on how to assign styles to my controls. What I'd like to do is set a global font family for the entire application.
在我的 App.xaml
文件中,我有以下内容
In my App.xaml
file I have the following
<Style TargetType="{x:Type Window}">
<Setter Property="FontFamily" Value="Helvetica, Arial" />
<Setter Property="FontSize" Value="13" />
</Style>
我已经尝试将目标类型更改为 Control
但这没有任何作用.我希望因为从技术上讲,一切都在 Window
控件中,所以一切都会按预期工作.
I've tried changing the target type to Control
but that's not doing anything. I would expect that since everything technically lives in a Window
control that everything would work as expected.
原来 TextBlock
控件不是从 Control
继承的.我假设这是大部分问题,因为我 90% 的文本都是 TextBlock
形式.
Turns out the TextBlock
control doesn't inherit from Control
. I'm assuming that's most of the problem because 90% of my text is in TextBlock
form.
在 CSS 中,我会这样做:
In CSS I would do something like this:
body {
font-family: Helvetica, Arial;
font-size: 13px;
}
我之前所做的是为控件创建一个样式,然后从中派生其他控件样式.无论出于何种原因,WPF 都不想直接从 Control 样式中获取 FontFamily 设置,但是如果它从基于 Control 的按钮样式中获取它,那么它就可以工作.如果我以后有时间,我会四处挖掘并找到以前的实现.
What I have previously done is create a Style for Control, then derive other control styles from it. For whatever reason, WPF doesn't want to take a FontFamily setting directly from a Control style, but if it takes it from a Button Style that is based on Control, then it works. If I get some time later on, I will dig around and find a previous implementation of this.
不记得我可能在哪里放了一个现成的例子,所以我做了一个:
Couldn't remember where I might have put a ready made example, so I made one:
<Style x:Key="ControlStyle" TargetType="Control">
<Setter Property="FontFamily" Value="Wingdings"/>
</Style>
<Style TargetType="Button" BasedOn="{StaticResource ControlStyle}"/>
另外,请记住,TextBlock 的样式不能基于 Control.Textblock 派生自 Framework 元素,而不是 Control.标签、复选框、文本框等衍生自 Control 衍生自 Framework Element.
Also, keep in mind, a style for TextBlock cannot be based on Control. Textblock derives from Framework element, not Control. Label, checkbox, Textbox, etc derive from Control which derives from Framework Element.
您可能需要为 Textblock 设置单独的样式.您可以做的一件事是设置字体系列资源并将您的顶级样式绑定到该资源.然后,如果它发生变化,您所要做的就是更改那个实例.
You will likely have to have a separate style for Textblock. One thing you can do is set a font family resource and bind your top level styles to that. Then if it changes, all you have to do is change that one instance.
<FontFamily x:Key="DefaultFont" >Ravie</FontFamily>
<Setter Property="FontFamily" Value="{DynamicResource DefaultFont}"/>