我写了一个blog post回来,其中包括一个自定义的ResourceDictionary实现,支持根据主题在两个ResourceDictionaries之间进行交换。
它可以与Visual Studio设计器(Cider)和Blend一起使用,但在Blend中使用该预览机制时不会交换到光源。不幸的是,由于Blend如何处理资源,它看起来在可预见的将来会保持这种状态。
您可以阅读原帖的其他信息,但我会在这里包含的代码:
namespace ThemeManagement {
/// <summary>
/// Provides automatic selection of resources based on the current theme
/// </summary>
public class ThemeResourceDictionary : ResourceDictionary
{
private ResourceDictionary lightResources;
private ResourceDictionary darkResources;
/// <summary>
/// Gets or sets the <see cref="ResourceDictioary"/> to use
/// when in the "light" theme
/// </summary>
public ResourceDictionary LightResources
{
get { return lightResources; }
set
{
lightResources = value;
if (!IsDarkTheme && value != null)
{
MergedDictionaries.Add(value);
}
}
}
/// <summary>
/// Gets or sets the <see cref="ResourceDictioary"/> to use
/// when in the "dark" theme
/// </summary>
public ResourceDictionary DarkResources
{
get { return darkResources; }
set
{
darkResources = value;
if (IsDarkTheme && value != null)
{
MergedDictionaries.Add(value);
}
}
}
/// <summary>
/// Determines if the application is running in the dark theme
/// </summary>
private bool IsDarkTheme
{
get
{
if (IsDesignMode)
{
return true;
}
else
{
return (Visibility)Application.Current
.Resources["PhoneDarkThemeVisibility"] == Visibility.Visible;
}
}
}
/// <summary>
/// Determines if the application is being run by a design tool
/// </summary>
private bool IsDesignMode
{
get
{
// VisualStudio sometimes returns false for DesignMode,
// DesignTool is our backup
return DesignerProperties.GetIsInDesignMode(this) ||
DesignerProperties.IsInDesignTool;
}
}
}
}
然后,您可以这样定义光/暗特定的资源(或者你可以把他们在自己的资源XAML文件):
<Application.Resources>
<custom:ThemeResourceDictionary>
<custom:ThemeResourceDictionary.LightResources>
<ResourceDictionary>
<BitmapImage x:Key="ThemedImage"
UriSource="/ThemeManagement;component/Content/ImageLight.png" />
</ResourceDictionary>
</custom:ThemeResourceDictionary.LightResources>
<custom:ThemeResourceDictionary.DarkResources>
<ResourceDictionary>
<BitmapImage x:Key="ThemedImage"
UriSource="/ThemeManagement;component/Content/ImageDark.png" />
</ResourceDictionary>
</custom:ThemeResourceDictionary.DarkResources>
</custom:ThemeResourceDictionary>
</Application.Resources>
然后,您可以参考它们在页面上是这样的:
<Image Source="{StaticResource ThemedImage}" />
谢谢。有用。 – MilkBottle