当前位置: 移动技术网 > IT编程>开发语言>.net > WPF——如何为项目设置全局样式。

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

2019年11月14日  | 移动技术网IT编程  | 我要评论

血溅归乡路,健康之路糖尿病,报名序号查询

    在项目中,需要为所有的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:,,,/resources/buttonstyle/basicbutton.xaml" />
                <!--  默认textbox样式  -->
                <resourcedictionary source="pack://application:,,,/resources/textboxstylebasic/textboxstylebasic.xaml" />
                <!--  默认checkbox样式  -->
            <resourcedictionary source="pack://application:,,,/resources/buttonstyle/basiccheckbox.xaml" />
                <!--  默认滚动条样式  -->               
      <resourcedictionary source="pack://application:,,,/resources/controlstyle/scrollviewbasic.xaml" />

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

2.

为控件写的样式和上文差不多,只是加上key。(没有key为全局样式,有key则需要进行键值引用)

 <style x:key="defaultcheckbox" targettype="{x:type checkbox}" />

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

  <resourcedictionary.mergeddictionaries>
        <resourcedictionary source="pack://application:,,,/resources/buttonstyle/basicbutton.xaml" />
        <resourcedictionary source="pack://application:,,,/resources/buttonstyle/basiccheckbox.xaml" />
        <resourcedictionary source="pack://application:,,,/resources/controlstyle/scrollviewbasic.xaml" />
        <resourcedictionary source="pack://application:,,,/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:,,,/resources/overwridedefaultcontrolstyles.xaml" />

 

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

 

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网