How do I match my controls' styles to the current theme? (WPF)

前端 未结 2 553
北海茫月
北海茫月 2020-12-16 04:00

If I create a custom control with WPF, how can I provide styles for the control that match the currently applied theme (Aero, Luna, Classic, etc.)?

For example I\'d

相关标签:
2条回答
  • 2020-12-16 04:18

    You can use different themes in WPF by loading/unloading resource dictionaries. These dictionaries should contain the styles for your controls. When you swap out dictionaries, WPF will apply the styles to your controls.

    for example if this were in WhiteStyle.xaml and you loaded it, your textblocks would all display text in a white-colored font.

    <Style TargetType="TextBlock">
        <Setter Property="Foreground" Value="White"/>
    </Style>
    

    if you swapped it out for BlackStyle.xaml which contains

    <Style TargetType="TextBlock">
        <Setter Property="Foreground" Value="Black"/>
    </Style>
    

    your textblocks would display text in a black-colored font. WPF handles alot of the details for us, we just have to tell it what the details are.

    Swapping out resource dictionaries is realatively simple, and I leave that to you to figure out. Googling "WPF Themes" is a good place to start.

    0 讨论(0)
  • 2020-12-16 04:25

    Some links that might be prove helpful:

    http://arbel.net/blog/archive/2006/11/03/Forcing-WPF-to-use-a-specific-Windows-theme.aspx

    http://www.browsoft.com/tutorials/DefaultTheme.html

    http://blogs.msdn.com/wpfsdk/archive/2007/07/31/using-themes-with-custom-controls.aspx

    Basically you create resource dictionaries for your custom controls named like this:

    Classic.xaml (“Classic” Windows 9x/2000 look on Windows XP.)
    Luna.NormalColor.xaml (Default blue theme on Windows XP.)
    Luna.Homestead.xaml (Olive theme on Windows XP.)
    Luna.Metallic.xaml (Silver theme on Windows XP.)
    Royale.NormalColor.xaml (Default theme on the Windows XP Media Center Edition operating system.)
    Aero.NormalColor.xaml (Default theme on the Windows Vista operating system.)
    

    Put the different styles for your controls in those files and they will be loaded based on the current theme of the OS.

    0 讨论(0)
提交回复
热议问题