WPF中控件擁有很多依賴屬性(Dependency Property),我們可以通過編寫自定義Style文件來控制控件的外觀和行為,如同CSS代碼一般。
總結一下WPF中Style樣式的引用方法:
一、內聯樣式
直接在控件的內部xaml代碼中書寫各種依賴屬性,如下:
1 <Button Height="30" Width="60" Background="Green" Foreground="White"> 2 </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#代碼:
1 Button btn =new Button(); 2 btn.SetValue(Button.StyleProperty, Application.Current.Resources["資源名稱"]);