如何将我的控件样式与当前主题相匹配?(WPF)

10
如果我使用WPF创建自定义控件,如何为该控件提供符合当前应用主题(Aero、Luna、Classic等)的样式?
例如,当使用Aero时,我想要应用以下样式:
<Style>
    <Setter Property="Background" Value="White"/>
</Style>
但是在使用Luna时应用不同的样式:
<Style>
    <Setter Property="Background" Value="#DFDFDF"/>
</Style>

我可以通过什么方式扩展基础主题以支持我的新控件吗?

2个回答

9

以下是一些可能有用的链接:

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

基本上,您需要为自定义控件创建资源字典,文件名应该如下所示:

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.)

将控件的不同样式放入这些文件中,它们将根据操作系统的当前主题进行加载。


这些链接很有帮助,谢谢。对我来说关键点是在AssemblyInfo.cs文件中进行更改 - 将[ThemeInfo]属性的themeDictionaryLocation从“None”切换到“SourceAssembly”。 - ajlane

0

你可以通过加载/卸载资源字典在WPF中使用不同的主题。这些字典应该包含控件的样式。当你切换字典时,WPF会将样式应用到你的控件上。

例如,如果这个样式在WhiteStyle.xaml中,并且你加载了它,那么你的文本块将显示白色字体的文本。

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

如果您将其替换为包含BlackStyle.xaml的文件

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

你的文本块将显示黑色字体。WPF为我们处理了很多细节,我们只需要告诉它这些细节是什么。

交换资源字典相对简单,我会留给你自己去解决。在谷歌上搜索“WPF主题”是一个不错的起点。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接