Некоторое время назад я написал сообщение в блоге , которое включало пользовательскую реализацию 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}" />