在运行时更改 xamarin.forms 颜色

changing xamarin.forms colors at runtime

我正在使用 xamarin.forms 制作一个应用程序,我已经设置了一个配色方案,我希望能够在设置中将其更改为深色风格或浅色风格,现在一切正常,除了每次 select 不同的配色方案后,我都必须重新启动应用程序。

这是我试图在运行时更改它的地方

   private void DarkThemeClick(object sender, EventArgs e)
    {
        database.DropTable(new StyleModel());
        database.CreateTable(new StyleModel());
        database.SaveItem(new StyleModel() { ThemeNum = 1 });
        App.ActiveStyle = new DarkStyle();
    }

    private void LightThemeClick(object sender, EventArgs e)
    {
        database.DropTable(new StyleModel());
        database.CreateTable(new StyleModel());
        database.SaveItem(new StyleModel() { ThemeNum = 0 });
        App.ActiveStyle = new LightStyle();
    }

这是我正在使用的项目示例,我想更改

上的颜色
    using System;
using TestXamForms.Style;
using Xamarin.Forms;

namespace TestXamForms.Helpers
{
class EntryValueCell : StackLayout
{

    public EntryValueCell(string key,int FieldIdx, string value = "",  bool isNumber = false)
    {
        Entry entry;
        Label label = new Label()
        {
            TextColor = App.ActiveStyle.LabelTextColor,
            Text = key,
            HorizontalOptions = LayoutOptions.End
        };
        if (isNumber)
        {
            entry = new Entry()
            {
                ClassId = FieldIdx.ToString(),
                TextColor = App.ActiveStyle.LabelTextColor,
                HorizontalOptions = LayoutOptions.FillAndExpand,
                Keyboard = Keyboard.Numeric,
                Text = value, 


            };
        }
        else
        {
            entry = new Entry()
            {
                ClassId = FieldIdx.ToString(),
                TextColor = App.ActiveStyle.LabelTextColor,
                HorizontalOptions = LayoutOptions.FillAndExpand,
                Keyboard = Keyboard.Text,
                Text = value
            };
        }

        BackgroundColor = App.ActiveStyle.StackLayoutBackground;
        Orientation = StackOrientation.Horizontal;
        VerticalOptions = LayoutOptions.FillAndExpand;
        Children.Add(label);
        Children.Add(entry);
    }
}
}

这是其中一种配色方案的示例

    using Xamarin.Forms;

   namespace TestXamForms.Style
 {
     public  class LightStyle : StyleBase
    {
       public LightStyle()
        {
        LabelTextColor = Color.Black;
        ButtonColor = Color.FromHex("337ab7");
        StackLayoutBackground = Color.FromHex("eff0f1");
        InputBackgroundColor = Color.White;
        PlaceHolderColor = Color.Gray;
        TableColor = Color.FromHex("e6e6e6");
        StacklayoutBorderColor = Color.Black;
       }
      }
     }

这里是上面文件继承的styleBase

using TestXamForms.Models;
using Xamarin.Forms;

namespace TestXamForms.Style
{
public class StyleBase : ModelBase
{
    public enum ThemeNum : int
    {
        Light = 0, Dark = 1
    }
    public Color LabelTextColor { get; set; }
    public Color ButtonColor { get; set; }
    public Color StackLayoutBackground { get; set; }
    public Color InputBackgroundColor { get; set; }
    public Color PlaceHolderColor { get; set; }

    public Color StacklayoutBorderColor { get; set; }

    public Color TableColor { get; set; }

    public int ThemeNums { get; set; }

}
}

这是 App.cs 文件的一部分,它在应用程序启动时加载配色方案

    static StyleBase activeStyle { get; set; }


    public static StyleBase ActiveStyle
    {
        get
        {
            if (activeStyle == null)
            {
                StyleModel styleBase = database.GetItems(new     StyleModel()).First();
                if (styleBase == null)
                {
                    database.SaveItem(new StyleModel() { ThemeNum = 0 }); //sets the default color scheme to light style 
                    styleBase = database.GetItems(new StyleModel()).First();
                }
                int themeNum = styleBase.ThemeNum;
                switch (themeNum)
                {
                    case (int)StyleBase.ThemeNum.Dark:
                        activeStyle = new DarkStyle();
                        break;
                    case (int)StyleBase.ThemeNum.Light:
                        activeStyle = new LightStyle();
                        break;
                }
            }
            return activeStyle;
        }
        set { } }

看看这个 blog post。特别是关于 DynamicResourcesStyles 的部分。

<Application
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="Your.App">
    <Application.Resources>
        <ResourceDictionary>
            <Color x:Key="backgroundColor">#33302E</Color>
            <Color x:Key="textColor">White</Color>
        </ResourceDictionary>
    </Application.Resources>
</Application>

现在设置您的资源

<Label Text="{Binding Name}" FontSize="Medium" FontAttributes = "Bold" TextColor = "{DynamicResource textColor}" LineBreakMode="NoWrap"/>
<Label Text="{Binding Text}" FontSize="Small" LineBreakMode="WordWrap" TextColor = "{DynamicResource textColor}"/>

现在您可以在代码中即时更改您的资源

App.Current.Resources ["backgroundColor"] = Color.White;
App.Current.Resources ["textColor"] = Color.Black;

如果您使用的是 2.3,您还可以尝试 built in themes

您面临的问题是所有内容都已呈现,并且您没有绑定任何 属性,这将重新呈现您在代码中对 UI 所做的更改。您可以采用 MVVM 方法并创建属性并绑定到它们并在 UI 线程中更改它们时通知它们。

如果您只对深色和浅色主题感兴趣,那么您可以使用内置的 Light Theme and Dark Theme. You can also create Custom Themes

A theme is added to a Xamarin.Forms application by including the Xamarin.Forms.Theme.Base Nuget package, plus an additional package that defines a specific theme (eg. Xamarin.Forms.Theme.Light) or else a local theme can be defined for the application.

除了自动设置常用控件的样式外,Light 和 Dark 主题目前还支持以下 classes,可以通过在这些控件上设置 StyleClass 来应用它们:

  • BoxView - 水平规则, 圆圈, 四舍五入

  • 图片 - 圆圈, 圆形, 缩略图

  • 按钮 - 默认, 基本的, 成功, 信息, 警告, 危险, Link, 小的, 大

  • 标签 - Header, 副标题, Body, Link, 逆

要向您的应用程序添加主题,请执行以下操作:

  1. 将 Nuget 包添加到您的项目中。

  2. 将主题添加到 App.xaml 中的资源词典

  3. 使用样式 class 在主题中应用预定义样式 classes。

    <Button Text="Button Class Default" StyleClass="Default" />
    <Button Text="Button Class Primary" StyleClass="Primary" />
    <Button Text="Button Class Success" StyleClass="Success" />
    

阅读有关主题的更多信息here