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>

注意这个,和前面的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>

效果如下:

如果我们改变系统地主题:

再次编译运行,则程序运行如下:

看不出区别~

但,若我们程序保持运行,改变主题,则程序界面随之改变如下:

这就是两者的区别。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值