1. 程式人生 > >WPF整理-使用使用者選擇主題的顏色和字型

WPF整理-使用使用者選擇主題的顏色和字型

“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>

"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>

效果如下:

如果我們改變系統地主題:

再次編譯執行,則程式執行如下:

看不出區別~

但,若我們程式保持執行,改變主題,則程式介面隨之改變如下:

這就是兩者的區別。