WPF中Style檔案的引用——使用xaml程式碼或者C#程式碼動態載入
阿新 • • 發佈:2019-02-09
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["資源名稱"]);