我寫了一個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