WPF 如何引入外部樣式
阿新 • • 發佈:2020-11-18
WPF 如何引入外部樣式
當我們給一些控制元件設定相同的屬性的時候,這時候,我們可以把這些屬性寫到一個Style裡面。
而其他頁面也有類似的控制元件也需要使用這個Style,這時候就需要把這個Style放在一個共通的檔案裡,然後引入這個Style檔案即可。有點像html引入CSS檔案一樣。
首先新建一個資源字典檔案,方法如下:
然後在裡面新增我們的樣式,如簡單寫一個Button的樣式:
<Style x:Key="BtnStyle" TargetType="Button"> <Setter Property="Height" Value="72" /> <Setter Property="Width" Value="150" /> <Setter Property="Foreground" Value="White" /> <Setter Property="Background" Value="Green" /> </Style>
然後在我們的窗體裡引用:
<Window.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Style/test.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Window.Resources>
這裡的Soure裡寫的是相對路徑,因為我的test.xmal是放在Style資料夾裡的,所以前面需要加Style。
使用的方法,如普通的方法是一樣的。
<Button x:Name="button" Grid.Column="1" Grid.Row="1" Style="{DynamicResource BtnStyle}" />
效果如下: