天天看點

WPF中Style檔案的引用——使用xaml代碼或者C#代碼動态加載

原文: 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["資源名稱"]);