在 WPF 中使用 App.xaml 中的静态资源更改所有 UI 元素的字体大小



我需要更改整个应用程序中所有文本的字体大小。

我尝试执行以下操作,但这不起作用:-

<Style x:Key="fontsize" TargetType="{x:Type FrameworkElement}">
<Setter Property="Control.FontSize" Value="20"/>
</Style>
<Style TargetType="{x:Type FrameworkElement}" BasedOn="{StaticResource fontsize}"/>

当我尝试按如下方式设置时,它工作正常,但不能应用于所有元素,并且需要将其应用于所有不同类型的元素。

<Style TargetType="TextBlock" BasedOn="{StaticResource fontsize}"/>
<Style TargetType="TextBox" BasedOn="{StaticResource fontsize}"/>
<Style TargetType="DataGridCell" BasedOn="{StaticResource fontsize}"/>
<Style TargetType="MenuItem" BasedOn="{StaticResource fontsize}"/>
<Style TargetType="DatePicker" BasedOn="{StaticResource fontsize}"/>

我还想问一下,有没有办法可以覆盖特定元素的全局样式,例如用户控件上的标题文本应该具有不同的大小?

in App.xaml

<Style TargetType="TextBlock">
<Setter Property="FontSize" Value="20"/>
<Setter Property="FontWeight" Value="Bold"/>
</Style>

在 App.xaml 中为窗口创建全局样式。

<Application.Resources>
<Style x:Key="WindowStyle" TargetType="{x:Type Window}">
<Setter Property="FontStyle" Value="Italic" />
<Setter Property="FontSize" Value="24" />
<Setter Property="Foreground" Value="Green"/>
</Style>
</Application.Resources>

并为所需的窗口设置该样式。

<Window x:Class="YourNamespace.MainWindow"  Style="{StaticResource WindowStyle}".....>

用于重写用户控件的样式

<local:UserControl1>
<local:UserControl1.Style>
<Style TargetType="UserControl">
<Setter Property="FontSize" Value="10"/>
</Style>
</local:UserControl1.Style> 
</local:UserControl1>

这涉及两个控件。 您可能会想"嘿,这个单元格或那个日历呢"。 他们的模板在文本块中显示文本。 在菜单项上设置标题或在标签上设置内容时,会生成文本块。

因此,您"只需要"在文本块和文本框上设置样式:

<Application.Resources>
<ResourceDictionary>
<Style TargetType="TextBlock">
<Setter Property="FontSize" Value="20"/>
</Style>
<Style TargetType="TextBox">
<Setter Property="FontSize" Value="20"/>
</Style>
</ResourceDictionary>
</Application.Resources>
</Application>

话虽如此。

正如克莱门斯指出的那样。

字体大小和样式依赖项属性被标记为继承,因此如果您只有主窗口,则可以对其进行设置。

不过,当您设置内容时,标签最终会带有文本块,这不仅仅是"显而易见的"。类似地,菜单项和标题。因此,我认为值得发布这个答案。

最新更新