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

来源:互联网 发布:光棍节程序员闯关 编辑:程序博客网 时间:2024/04/30 06:46

  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["资源名称"]);
3 1
原创粉丝点击