如何使用 Xamarin.Forms 中的转换器将文本转换为颜色?

msh*_*hwf 4 c# xaml ivalueconverter xamarin.forms

我想固定枚举我的应用程序颜色,即文本颜色、分隔符颜色和背景颜色,我不想每次使用时都输入相同的颜色,所以我想我可以传递对象名称(例如分隔符),并在转换器中将其转换为所需的颜色:这是我对IValueConverter类的实现:

class AppColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is string)
        {
            var color = (string)value;
            switch (color)
            {
                case "separator":
                    return Color.FromHex("c2bca8");
                case "text":
                    return Color.FromHex("96907e");
                default:
                    return Color.Default;
            }
        }
        else
            return null;

    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我从我对数据绑定的了解中使用了它,但我只是想将一个字符串传递给 color 属性,并且转换器处理它,我添加了一个 ResourceDictionary:

  <Controls:CustomPage.Resources>
        <ResourceDictionary>
            <Converters:AppColorConverter x:Key="colorConverter"/>
        </ResourceDictionary>
    </Controls:CustomPage.Resources>
Run Code Online (Sandbox Code Playgroud)

但是我如何使用它,这不起作用:

<Label Text="English" 
       VerticalOptions="CenterAndExpand" 
       HorizontalOptions="EndAndExpand" 
       TextColor="{separator, Converter=colorConverter}"/>
Run Code Online (Sandbox Code Playgroud)

Dav*_*isk 5

您还可以将颜色值存储在 ResourceDictionary 中,如下所示:

<Color x:Key="ThemeBlue">#2499CE</Color>
Run Code Online (Sandbox Code Playgroud)

然后在您的 switch 语句中,使用以下语法:

return Application.Current.Resources["ThemeBlue"];
Run Code Online (Sandbox Code Playgroud)

这样您就可以在您站点上的所有转换器中重复使用您的颜色值,并在一个地方(您的 ResourceDictionary)管理它们。

编辑

您可以在尝试时进行绑定,但您需要更新语法。尝试这个:

<Label Text="English" VerticalOptions="CenterAndExpand" HorizontalOptions="EndAndExpand" TextColor="{Binding ., Converter={StaticResource colorConverter}, ConverterParameter='separator'}" />
Run Code Online (Sandbox Code Playgroud)

在您的值转换器中,使用参数对象而不是值对象 - 我们将“分隔符”作为本示例中的参数传递。但是,我不推荐这种方法。

if (parameter is string)
        {
            var color = (string)parameter;
            ... etc ...
Run Code Online (Sandbox Code Playgroud)

我认为 Diego 只使用一种风格的想法是要走的路,但这可以回答你的问题并在我的测试中起作用。