How to change FontFamily for Textbox while defined in Window

时间:2015-06-26 09:28:26

标签: c# wpf xaml styles

I have an issue with defining FontFamily to my textboxes applicationwide, because my font family is defined at window level with this style :

<Style TargetType="Window" >
    <Setter Property="FontFamily" Value="Lucida Sans Unicode"/>
    <Setter Property="FontSize" Value="10pt"/>
</Style>

I have defined the font-family for my textboxes this way :

<Style TargetType="{x:Type TextBox}">
    <Setter Property="FontFamily" Value="Arial"/>
    <Setter Property="FontSize" Value="10pt"/>
</Style>

However, my TextBox style is not applied, and the text into the textboxes is still Lucida, and not Arial. How can I do that ? Is there a css-like !important equivalent in XAML style to override previous one ?

I notice that I really appreciate a XAML way to perform it on ResourceDictionaries.

Thanks for answers

1 个答案:

答案 0 :(得分:-1)

It is working for me. I defined two styles, one for window, one special for text box. Special style wins and result is Arial 30pt. If I comment special style then window style is applied for textBox and comic sans 20pt appear.

See code:

<Window x:Class="WpfApplication3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication3"
        Title="MainWindow" Height="350" Width="525">
  <Grid>
    <TextBox Text="Hello!"/>
  </Grid>
</Window>

Application resources:

<Application x:Class="WpfApplication3.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
    <Style TargetType="Window" >
      <Setter Property="FontFamily" Value="Comic Sans MS"/>
      <Setter Property="FontSize" Value="20pt"/>
    </Style>
    <Style TargetType="{x:Type TextBox}">
      <Setter Property="FontFamily" Value="Arial"/>
      <Setter Property="FontSize" Value="30pt"/>
    </Style>
  </Application.Resources>
</Application>