如何设置WPF应用程序的默认字体?

我想能够为我的WPF应用程序定义一个字体家族。 最好使用资源字典作为从App.xaml引用的主题。 我试着创build一个Style如下:

 <Style TargetType="{x:Type Control}"> <Setter Property="FontFamily" Value="Segoe UI" /> </Style> 

但是这不起作用。 将该types设置为TextBlock适用于大多数控件,但有些控件不适用这些控件。

我知道你可以在窗口上设置字体,并让该窗口的所有子控件inheritance字体。 但是我认为任何对话窗口都会回到默认字体,这不正是我想要的。

有任何想法吗?

假设你的Window子类不重写DefaultStyleKey ,你可以简单地将它添加到你的Window样式,因为TextElement.FontFamilyProperty是一个inheritance的属性:

 <Style TargetType="{x:Type Window}"> <Setter Property="FontFamily" Value="Segoe UI" /> </Style> 

您还需要在InitializeComponent调用之后将以下内容添加到您的App构造函数中:

 FrameworkElement.StyleProperty.OverrideMetadata(typeof(Window), new FrameworkPropertyMetadata { DefaultValue = FindResource(typeof(Window)) }); 

工作原理:App对象完成初始化后,其中指定的窗口样式将成为所有窗口的默认样式。

大多数提议的解决scheme不适合我。 我简单的解决scheme

将此添加到App.xaml:

 <Style TargetType="{x:Type Window}"> <Setter Property="FontSize" Value="14" /> </Style> 

在你的MainWindow构造函数中(在InitializeComponent之后)添加它:

 Style = (Style)FindResource(typeof(Window)); 

我find了这个 :

 TextElement.FontFamilyProperty.OverrideMetadata( typeof(TextElement), new FrameworkPropertyMetadata( new FontFamily("Comic Sans MS"))); TextBlock.FontFamilyProperty.OverrideMetadata( typeof(TextBlock), new FrameworkPropertyMetadata( new FontFamily("Comic Sans MS"))); 

一个简单的方法来编程:

 public MainWindow() { this.FontFamily = new FontFamily("Segoe UI"); } 

App.xaml尝试这个简单的解决方法(不需要后面的代码):

 <SolidColorBrush x:Key="ForeBrush" Color="Blue" /> <Style x:Key="GenericTextStyle"> <!-- Generic control forecolor definition --> <Setter Property="Control.Foreground" Value="{StaticResource ForeBrush}" /> <!-- Add a definition for each unworking nested control --> <Style.Resources> <Style TargetType="{x:Type Label}"> <Setter Property="Foreground" Value="{StaticResource ForeBrush}" /> </Style> </Style.Resources> </Style> 

只要将你的Windows风格绑定到这个。 为我完美的作品。 只有一些属性需要在嵌套树中定义。 例如,属性FontSize只能在通用部分中指定。

我不知道为什么要这样做。 这很奇怪,因为标签应该从Control派生。 任何人有任何想法呢?