【问题标题】:How to change FontFamily for Textbox while defined in Window如何在 Window 中定义时更改文本框的 FontFamily
【发布时间】:2015-06-26 09:28:26
【问题描述】:

我在将 FontFamily 定义为应用程序范围的文本框时遇到问题,因为我的字体系列是在窗口级别使用这种样式定义的:

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

我以这种方式为我的文本框定义了字体系列:

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

但是,我的 TextBox 样式没有应用,文本框中的文本仍然是 Lucida,而不是 Arial。 我怎样才能做到这一点 ? XAML 样式中是否有类似 css 的 !important 等效项来覆盖之前的?

我注意到我非常欣赏在 ResourceDictionaries 上执行它的 XAML 方式。

感谢回答

【问题讨论】:

  • 这很有趣。您能否确认您是在 App.xaml 中而不是在每个窗口中设置这些样式?
  • 在 App.xaml 和 Window 中,我都将它们定义为在运行时动态加载的 ResourceDictionary
  • 整个应用程序的窗口/控制级别设置看起来很奇怪(我不完全理解)。请在此处查看 Gishu 的答案:stackoverflow.com/questions/431940/… 和 Nicolas 的此处:stackoverflow.com/questions/4279773/…

标签: c# wpf xaml styles


【解决方案1】:

它对我有用。我定义了两种样式,一种用于窗口,一种用于文本框。特殊风格获胜,结果是 Arial 30pt。如果我评论特殊样式,则将窗口样式应用于 textBox 并出现 20pt 漫画。

见代码:

<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 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>

【讨论】:

  • 在我尝试运行它之前,这对我来说是完全明智的。我在设计模式下得到了正确的结果,但在调试期间却没有。
  • 事实上,用 key 定义样式使解决方案有效,所以我会这样做只是因为我所有的窗口都继承了一个
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-21
  • 2021-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
相关资源
最近更新 更多