“Sometimes it's useful to use one of the selected colors or fonts the user has chosen in the
Windows Control Panel Personalization applet (or the older Display Settings in Windows XP),
such as Window caption, Desktop color, and Selection color. Furthermore, an application
may want to react dynamically to changes in those values. This can be achieved by accessing
special resource keys within the SystemColors and SystemFonts classes.”
有時候,我們想要使用用戶在控制面板中選擇的主題的顏色,或是我們希望我們的程序能夠跟着用戶選擇不同的主題,變換相應的顏色。這時候我們可以通過訪問SystemColors和SystemFonts類的特定的Resource keys。
Code Snip如下:
<Window x:Class="UsingUserSelectedColorsAndFonts.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <StackPanel > <TextBlock Text="Hello from Active Caption Font" FontFamily="{ DynamicResource {x:Static SystemFonts.CaptionFontFamilyKey}}" FontSize="{ DynamicResource {x:Static SystemFonts.CaptionFontSizeKey}}"/> <Rectangle Height="100" Stroke="DarkViolet" StrokeThickness="10" Fill="{DynamicResource {x:Static SystemColors.DesktopBrushKey}}"/> </StackPanel> </Window>
注意這個,和前面的WPF整理-XAML訪問靜態屬性 的對比:
"XAML provides an easy way to set values of properties—type converters and the extended property syntax allow for flexible setting of values. However, some things cannot be expressed as a simple value, such as setting a property to the value of some static property."
這個相對比較簡單,知道就行,Code Snip如下:
<StackPanel> <Ellipse Stroke="Black" Height="50" Fill="{x:Static SystemColors.DesktopBrush}"/> <Rectangle Stroke="Black" Height="50" Fill="{x:Static SystemColors.ActiveCaptionBrush}"/> </StackPanel>
兩者采用不同的方法實現相同的效果。
對比如下:
<StackPanel > <TextBlock Text="Hello from Active Caption Font" FontFamily="{ DynamicResource {x:Static SystemFonts.CaptionFontFamilyKey}}" FontSize="{ DynamicResource {x:Static SystemFonts.CaptionFontSizeKey}}"/> <Rectangle Height="100" Stroke="DarkViolet" StrokeThickness="10" Fill="{DynamicResource {x:Static SystemColors.DesktopBrushKey}}"/> <StackPanel> <TextBlock Text="Hello from Active Caption Font" FontFamily="{ x:Static SystemFonts.CaptionFontFamily}" FontSize="{ x:Static SystemFonts.CaptionFontSize}"/> <Rectangle Height="100" Stroke="DarkViolet" StrokeThickness="10" Fill="{x:Static SystemColors.DesktopBrush}"/> </StackPanel> </StackPanel>
效果如下:
如果我們改變系統地主題:
再次編譯運行,則程序運行如下:
看不出區別~
但,若我們程序保持運行,改變主題,則程序界面隨之改變如下:
這就是兩者的區別。