WPF——如何为项目设置全局样式。

时间:2019-11-14
本文章向大家介绍WPF——如何为项目设置全局样式。,主要包括WPF——如何为项目设置全局样式。使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

    在项目中,需要为所有的Button、TextBox设置一个默认的全局样式,一个个的为多个控件设置相同的样式显然是不明智的。在WPF中可以通过资源设置全局样式,主要有俩种方法:

1.第一种就是把写好按钮的样式,不写Key,然后在App.xaml中引用。

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style  TargetType="{x:Type CheckBox}" />
</ResourceDictionary>
          <!--  默认Button样式  -->
              <ResourceDictionary Source="pack://application:,,,/EkingHis.App.Products.Emr;component/Resources/ButtonStyle/BasicButton.xaml" />
                <!--  默认TextBox样式  -->
                <ResourceDictionary Source="pack://application:,,,/EkingHis.App.Products.Emr;component/Resources/TextBoxStyleBasic/TextBoxStyleBasic.xaml" />
                <!--  默认CheckBox样式  -->
            <ResourceDictionary Source="pack://application:,,,/EkingHis.App.Products.Emr;component/Resources/ButtonStyle/BasicCheckbox.xaml" />
                <!--  默认滚动条样式  -->               <ResourceDictionary Source="pack://application:,,,/EkingHis.App.Products.Emr;component/Resources/ControlStyle/ScrollViewBasic.xaml" />
      

这种方式有多少个控件就需要在APP中累砌多少个引用,会使配置文件杂乱冗余,而且由于默认样式没有Key,控制不够灵活,所以再介绍下第二种方法。

2.

为控件写的样式和上文差不多,只是加上Key。

 <Style x:Key="DefaultCheckBox" TargetType="{x:Type CheckBox}" />

新建一个资源,统一管理所有的控件样式资源。通过BaseOn继承带Key的样式,转换为默认全局样式,然后只需要在App中引用即可。这样即使需要写几十上百个样式,APP中也只需要一行代码。

  <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="pack://application:,,,/EkingHis.App.Products.Emr;component/Resources/ButtonStyle/BasicButton.xaml" />
        <ResourceDictionary Source="pack://application:,,,/EkingHis.App.Products.Emr;component/Resources/ButtonStyle/BasicCheckbox.xaml" />
        <ResourceDictionary Source="pack://application:,,,/EkingHis.App.Products.Emr;component/Resources/ControlStyle/ScrollViewBasic.xaml" />
        <ResourceDictionary Source="pack://application:,,,/EkingHis.App.Products.Emr;component/Resources/TextBoxStyleBasic/TextBoxStyleBasic.xaml" />
    </ResourceDictionary.MergedDictionaries>
    <Style BasedOn="{StaticResource DefaultButton}" TargetType="Button" />
    <Style BasedOn="{StaticResource DefaultCheckBox}" TargetType="CheckBox" />
    <Style BasedOn="{StaticResource DefaultScrollViewer}" TargetType="ScrollViewer" />
    <Style BasedOn="{StaticResource DefaultTextBox}" TargetType="TextBox" />
</ResourceDictionary>

App中:

 <ResourceDictionary Source="pack://application:,,,/EkingHis.App.Products.Emr;component/Resources/OverwrideDefaultControlStyles.xaml" />

总结:如果只需要设置一俩个控件的全局样式,第一个即可,设置多个控件样式的话,还是建议第二种。另外:在APP.xaml中,在最下面的引用优先级最高。

原文地址:https://www.cnblogs.com/king10086/p/11855118.html