我需要在通用Windows應用程序的運行時更改應用程序的TextBlocks的顏色。更新通用Windows應用程序中的資源XAML
通用的Windows應用程序不支持動態資源使用樣式
<Style x:Key="MyText" TargetType="TextBlock">
<Setter Property="Foreground" Value="{StaticResource TextColor}" />
</Style>
我的問題是我一直在探索失敗的幾個不同的方法來改變TextBlock的
<TextBlock Text="Test" Style="{StaticResource MyText}"/>
的顏色: 如何在運行時更改TextBlock的顏色?
接下來是所有試圖改變顏色:
起初,我也跟着這篇文章+視頻Dynamically Skinning Your Windows 8 App和我存儲TextColor
在一個單獨的字典文件,我可以換入或換出MergedDictionaries
Day.xaml
包含<SolidColorBrush x:Key="TextColor" Color="#FFDDEEFF" />
Night.xaml
包含<SolidColorBrush x:Key="TextColor" Color="#FFFFDD99" />
在代碼:
ResourceDictionary _nightTheme = new ResourceDictionary() { Source = new Uri("ms-appx:///Themes/Night.xaml") };
ResourceDictionary _baseTheme = new ResourceDictionary() { Source = new Uri("ms-appx:///Themes/MyApp.xaml") };
// OnLaunched - I set a default theme to prevent exceptions
Application.Current.Resources.MergedDictionaries.Add(_dayTheme);
// Method that changes theme:
if (NightFall)
{
Application.Current.Resources.MergedDictionaries.Remove(_dayTheme);
Application.Current.Resources.MergedDictionaries.Add(_nightTheme);
}
else
{
Application.Current.Resources.MergedDictionaries.Remove(_nightTheme);
Application.Current.Resources.MergedDictionaries.Add(_dayTheme);
}
當這個沒有工作,我想我需要明確的字典:
ResourceDictionary _baseTheme = new ResourceDictionary() { Source = new Uri("ms-appx:///Themes/MyApp.xaml") };
// Method that changes theme:
Application.Current.Resources.MergedDictionaries.Clear();
Application.Current.Resources.MergedDictionaries.Add(_baseTheme);
if (NightFall)
{
Application.Current.Resources.MergedDictionaries.Add(_nightTheme);
}
else
{
Application.Current.Resources.MergedDictionaries.Add(_dayTheme);
}
我也試着在更改字典的方法中刷新幀,無效
var frame = Window.Current.Content as Frame;
frame.Navigate(frame.Content.GetType());
在另一個嘗試我試圖創建一個字典,運行和更新
ResourceDictionary _dynamicTheme = new ResourceDictionary();
// OnLaunched
_dynamicTheme.Add("TextColor", new SolidColorBrush(Windows.UI.Colors.Chocolate));
Application.Current.Resources.MergedDictionaries.Add(_dynamicTheme);
// Method that changes theme
_dynamicTheme.Remove("TextColor");
_dynamicTheme.Add("TextColor", new SolidColorBrush(NightFall ? Windows.UI.Colors.Chocolate : Windows.UI.Colors.Cornsilk));
最後,我意識到,也許StaticResource
使顏色不變的,所以我決定試試ThemeResource
。我修改我的主題:
<Style x:Key="MyText" TargetType="TextBlock">
<Setter Property="Foreground" Value="{ThemeResource MyTextColor}" />
</Style>
Day.xaml
<ResourceDictionary.ThemeDictionaries>
<ResourceDictionary x:Key="Default">
<SolidColorBrush x:Key="MyTextColor" Color="#FFDDEEFF" />
</ResourceDictionary>
</ResourceDictionary.ThemeDictionaries>
Night.xaml
<ResourceDictionary.ThemeDictionaries>
<ResourceDictionary x:Key="Default">
<SolidColorBrush x:Key="MyTextColor" Color="#FFFFDD99" />
</ResourceDictionary>
</ResourceDictionary.ThemeDictionaries>
我換的方式進出Application.Current.Resources.MergedDictionaries
的就像在以前的嘗試。 同樣,顏色沒有變化,即使我假刷新的Frame