WPF全局字体大小

Jos*_*ose 66 wpf fonts

我正在创建一个WPF应用程序,我想知道能够更改ui中每个元素的字体大小的最佳方法.我是否创建资源字典并设置样式以设置我使用的所有控件的字体大小?

什么是最佳做法?

Car*_*rlo 86

我这样做:

<Window.Resources>
        <Style TargetType="{x:Type Control}" x:Key="baseStyle">
            <Setter Property="FontSize" Value="100" />
        </Style>
        <Style TargetType="{x:Type Button}" BasedOn="{StaticResource baseStyle}"></Style>
        <Style TargetType="{x:Type Label}" BasedOn="{StaticResource baseStyle}"></Style>
        <Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource baseStyle}"></Style>
        <Style TargetType="{x:Type ListView}" BasedOn="{StaticResource baseStyle}"></Style>
        <!-- ComboBox, RadioButton, CheckBox, etc... -->
    </Window.Resources>
Run Code Online (Sandbox Code Playgroud)

这样,如果我想要更改所有控件,我只需要更改"baseStyle"样式,其余的只是继承它.(那就是那些基于AnyOn属性的东西,如果你在继承的样式中创建其他setter,你也可以扩展基本样式)

  • 如果您需要动态更改字体大小,请确保所有这些都声明为DynamicResource,在样式和样式引用中都指向"baseStyle". (3认同)
  • @Ian Boyd:但这家伙只想改变他所有控件的字体大小,而不是控件的大小.你所谈论的是一个完全不同的问题. (2认同)

Mat*_*ze 40

FontSizeProperty继承自Parent Control.所以你只需要更改主窗口的FontSize.

如果您不需要动态行为,这应该有效:

将Window的样式添加到ResourceDictionary

<Style TargetType="{x:Type Window}">
     <Setter Property="FontSize" Value="15" />
</Style>
Run Code Online (Sandbox Code Playgroud)

将样式应用于主窗体(不会隐式应用,因为它是派生类型)

 Style = (Style)FindResource(typeof (Window));
Run Code Online (Sandbox Code Playgroud)

  • 为什么要为单个元素创建样式?为什么不直接在元素上使用 `&lt;Window FontSize="15"&gt;` 呢? (4认同)
  • 编辑:不起作用(在任何情况下使用框架4.5). (2认同)

小智 27

另一种选择是将FontFamily和FontSize定义为资源.

<FontFamily x:Key="BaseFontFamily">Calibri</FontFamily>
<sys:Double x:Key="BaseFontSize">12</sys:Double>
Run Code Online (Sandbox Code Playgroud)

这样你就可以在你的setter中使用它们.

  • 必须导入_xmlns:sys ="clr-namespace:System; assembly = mscorlib"_这个方法工作得很完美. (5认同)

Jan*_*sha 24

<Window> 有一个属性FontSize.

因此,如果要更改该窗口中所有元素的fontsize,可以在元素中设置所需的fontsize.

<Window FontSize="12">

</Window>
Run Code Online (Sandbox Code Playgroud)


Vip*_*pul 9

Application.Current.MainWindow.FontSize = _appBodyFontSize;
Run Code Online (Sandbox Code Playgroud)

这样您也可以在运行时更改字体大小.


小智 6

TextElement.FontSize 是一个继承属性,这意味着您只需在根元素处设置字体大小,所有子元素都将使用该大小(只要您不手动更改它们)


Chr*_*col 5

对于 WPF 中的任何样式,您都应该有一个单独的资源字典,其中包含您的应用程序的样式。

如果您想要在整个应用程序中重复使用单个字体大小,那么只需为该字体大小创建一个样式。您可以给它一个唯一的名称/键以明确使用,或者您可以设置一个将超越整个应用程序的 targetType。

显式键:

<Style
    x:Key="MyFontSize"
    TargetType="TextBlock">
    <Setter
        Property="FontSize"
        Value="10" />
</Style>

<Control
    Style="{StaticResource MyFontSize}" />
Run Code Online (Sandbox Code Playgroud)

*请注意,此样式可与具有 contentPresenters 的控件一起使用

对于应用程序中的所有文本块:

<Style
    TargetType="TextBlock">
    <Setter
        Property="FontSize"
        Value="10" />
</Style>

<TextBlock
        Text="This text will be size 10" />
Run Code Online (Sandbox Code Playgroud)