问题描述
我想让用户可以选择我的 Xamarin.Forms 应用程序 UI 主题。我应该更改应用程序静态资源中的颜色值。
<Application.Resources>
<ResourceDictionary x:Name="ColorResources">
<Color x:Key="BgBar">#ffffff</Color>
<Color x:Key="BgHeaderShellMenu">#b3e5fc</Color>
<Color x:Key="BgMenu">#b3e5fc</Color>
<Color x:Key="BgMainPage">#b3e5fc</Color>
<Color x:Key="BgMainPageMenu">#b3e5fc</Color>
<Color x:Key="ForeGroundBar">#82b3c9</Color>
<Color x:Key="SelectedTabBar">#82b3c9</Color>
<Color x:Key="disabledTabBar">#575757</Color>
<Color x:Key="TtileTabBar">#82b3c9</Color>
<Color x:Key="UnselectedTabBar">#b3e5fc</Color>
<Color x:Key="UnSelectedTabBarLable">#82b3c9</Color>
<Color x:Key="MenuText">#82b3c9</Color>
<Color x:Key="Border">#82b3c9</Color>
<Color x:Key="SelectedTabBarLable">#b3e5fc</Color>
<Color x:Key="MenuLabel">#82b3c9</Color>
<Color x:Key="Primary">#2196F3</Color>
<Color x:Key="Dark">#b3e5fc</Color>
<Style targettype="Button">
<Setter Property="TextColor" Value="White"></Setter>
<Setter Property="visualstatemanager.VisualStateGroups">
<VisualStateGroupList>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="normal">
<VisualState.Setters>
<Setter Property="BackgroundColor" Value="{StaticResource BgBar}" />
</VisualState.Setters>
</VisualState>
<VisualState x:Name="disabled">
<VisualState.Setters>
<Setter Property="BackgroundColor" Value="#332196F3" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateGroupList>
</Setter>
</Style>
</ResourceDictionary>
</Application.Resources>
这是我的应用程序静态资源,但我无法更改它的值,因为它们都是 readonly
所以我尝试了这个:
private static List<Tuple<string,string>> DarkThemeKVs = new List<Tuple<string,string>>()
{
new Tuple<string,string>("BgBar","#121212"),new Tuple<string,string>("BgHeaderShellMenu",string>("BgMainPage",string>("BgMainPageMenu",string>("BgMenu",string>("ForeGroundBar","#cc2402"),string>("SelectedTabBar",string>("disabledTabBar","#575757"),string>("TtileTabBar",string>("UnselectedTabBar",string>("UnSelectedTabBarLable",string>("MenuText",string>("Border",string>("SelectedTabBarLable",string>("MenuLabel",};
在初始化组件之后:
if (Theme == "darktheme")
{
ResourceDictionary Rd = new ResourceDictionary();
foreach (var item in this.DarkThemeKVs)
{
Rd.Add(item.Item1,item.Item2);
}
this.Resources = Rd;
}
但是我遇到了一个例外,因为值不能是字符串。 值的类型应该是这样的:
我该怎么办? 这个类型在c#中叫什么名字?
解决方法
将颜色添加为 Color
,而不是 string
:
foreach (var item in DarkThemeKVs)
{
Rd.Add(item.Item1,Color.FromHex(item.Item2));
}