WPF中Style文件的引用——使用xaml代码或者C#代码动态加载

  WPF中控件拥有很多依赖属性(Dependency Property),我们可以通过编写自定义Style文件来控制控件的外观和行为,如同CSS代码一般。
  总结一下WPF中Style样式的引用方法:

  一、内联样式

  直接在控件的内部xaml代码中书写各种依赖属性,如下:

<Button Height="30" Width="60" Background="Green" Foreground="White">
</Button>

  这种方式比较直接方便,适用于单个控件、代码量较少的Style设置,代码不能重用。
  

  二、嵌入样式:

  在窗体(Window)或者页面(Page)的资源节点下面(Window.Resources或者Page.Resources)添加Style代码,这样在整个窗体或者页面范围内可以实现Style代码重用。
  第1步,书写Style代码:

<Window.Resources>
    <Style x:Key="myBtnStyle" TargetType="{x:Type Button}">
        <Setter Property="Height" Value="72" />
        <Setter Property="Width" Value="150" />
        <Setter Property="Foreground" Value="Red" />
        <Setter Property="Background" Value="Black" />
        <Setter Property="HorizontalAlignment" Value="Left" />
        <Setter Property="VerticalAlignment" Value="Top" />
    </Style>
</Window.Resources>

  第2步,在Button的xaml代码中引用Style:
  

<Button Style="{StaticResource myBtnStyle}"></Button>
  三、外联样式:

  前面说的两种方式,都无法设置整个应用程式里面的全局Style,现在我们介绍全局设置Style的方式。
  1.新建一个.xaml的资源文件,如/Theme/Style.xaml。
  2.在该文件中编写样式代码:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:System="clr-namespace:System;assembly=mscorlib">
    <Style x:Key="myBtnStyle" TargetType="Button">
    <Setter Property="Height" Value="72" />
    <Setter Property="Width" Value="150" />
    <Setter Property="Foreground" Value="White" />
    <Setter Property="Background" Value="Blue" />
    <Setter Property="HorizontalAlignment" Value="Left" />
    <Setter Property="VerticalAlignment" Value="Top" />
    </Style>
</ResourceDictionary>

  3.在App.xaml文件中的<Applictaion.Resources>节点下添加<ResourceDictionary>节点:
  

<Application.Resources> 
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/应用名称;component/Theme/Style.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

  这种方式相比前面两种使得样式和结构又更进一步分离了。在App.xaml引用,是全局的,可以使得一个样式可以在整个应用程序中能够复用。在普通页面中引用只能在当前页面上得到复用。

  四、使用C#代码动态加载Style

  1.假设应用程式用已经有了全局的资源文件(上面的方法中有介绍)。
  2.编写C#代码:
  

Button btn =new  Button();
btn.SetValue(Button.StyleProperty, Application.Current.Resources["资源名称"]);
  • 6
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值