【问题标题】:How to apply a WPF style to all elements of a particular type?如何将 WPF 样式应用于特定类型的所有元素?
【发布时间】:2011-01-02 07:55:12
【问题描述】:
<Window.Resources>   
 <Style TargetType="{x:Type Button}">    
   <Setter Property="FontFamily" Value="Times New Roman" />   
   <Setter Property="FontSize" Value="30" />    
   <Setter Property="FontWeight" Value="Bold" />     
   <Setter Property="Background" Value="#FFCA5132" /> 
 </Style>
</Window.Resources>

上面的代码看起来像是将 WPF 样式应用于特定窗口中的所有按钮的正确选择。但我想将这种样式应用于我程序中的所有按钮。 我想我需要在&lt;Application.Resources&gt;&lt;/Application.Resources&gt; 中写下这段代码。但它不运行。我该怎么做?

【问题讨论】:

  • 在 Application.Resources 中编写此代码时会发生什么。你得到一个编译器错误吗?如果是这样,你能告诉我们错误是什么吗?
  • 那里,格式化你的代码。为了将来参考,在每行或代码之前放置四个空格,对于内联代码like this,用反引号将其括起来(asdasd)。现在,问题是,当您将其放入 Application.Resources 时会发生什么?

标签: wpf styles


【解决方案1】:

&lt;Application.Resources&gt;ResourceDictionary。您不能像在代码中那样添加ResourceDictionaryStyle。将Style 放在ResourceDictionary 中,如下所示:

<Application.Resources>     

 <ResourceDictionary Source="/PresentationFramework.Aero
                        , Version=3.0.0.0,Culture=neutral
                        , PublicKeyToken=31bf3856ad364e35
                        , ProcessorArchitecture=MSIL;component/themes/aero.normalcolor.xaml">            
    <ResourceDictionary.MergedDictionaries>
     <ResourceDictionary Source="Style\AppStyle.xaml"></ResourceDictionary>
    </ResourceDictionary.MergedDictionaries>

    <Style TargetType="{x:Type Button}">
      <Setter Property="FontFamily" Value="meiryo" />
      <Setter Property="FontSize" Value="12" />
    </Style>   
  </ResourceDictionary>
</Application.Resources>

【讨论】:

  • 感谢您的建议。但它仍然无法运行。顺便说一句,我有另一个解决方案。在 AppStyle.xaml 文件中,我为窗口窗体创建了一个样式,并将我的按钮样式放在那里。它运行正常!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-19
  • 1970-01-01
  • 2014-12-08
  • 2013-10-28
  • 2012-01-29
  • 2015-11-09
相关资源
最近更新 更多