如何在Xamarin Forms中使用转换器将布尔值转换为文本和颜色

s71maibg  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(122)

我想使用布尔值绑定FontAwesome/MaterialFont图标和颜色。我已成功绑定字体图标,但无法绑定颜色。
isSQL是布尔值

密码...

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is bool boolValue)
        {
            string trueFontIcon = "\U000f05e0"; 
            string falseFontIcon = "\U000f05d6";

            Color trueColor = Color.Green;
            Color falseColor = Color.Red;

            return boolValue ? (trueFontIcon,trueColor) : (falseFontIcon, falseColor);
        }
        return ("\U000f1522", Color.Gray); 
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value;
    }

字符串

XAML...

<ResourceDictionary>
    <local:BooleanToFontIconConverter x:Key="BooleanToFontIconConverter" />
</ResourceDictionary>


<Label Grid.Column="1" tooltip:TooltipEffect.Text="{Binding sqlMessage}" FontFamily="MaterialFont">
    <Binding Path="isSQL" Converter="{StaticResource BooleanToFontIconConverter}" />
</Label>

5anewei6

5anewei61#

如果你想使用一个转换器来转换文本和文本颜色,你可以尝试使用一个转换器参数。
使用绑定时,

<Label Grid.Column="1" tooltip:TooltipEffect.Text="{Binding sqlMessage}" FontFamily="MaterialFont"
       Text="{Binding isSQL,Converter={StaticResource BooleanToFontIconConverter},ConverterParameter="Text"}"
       TextColor="{Binding isSQL,Converter={StaticResource BooleanToFontIconConverter},ConverterParameter="TextColor"}">
</Label>

字符串
所以在BooleanToFontIconConverter中,可以根据传入的ConverterParameter来决定返回FontIcon还是TextColor,

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    string param = parameter as string;
    
    if (value is bool boolValue)
    {
        string trueFontIcon = "\U000f05e0";
        string falseFontIcon = "\U000f05d6";

        Color trueColor = Color.Green;
        Color falseColor = Color.Red;

        if(param == "Text")
        {
            return boolValue ? trueFontIcon : falseFontIcon;
        }
        else
        {
            return boolValue ? trueColor : falseColor;
        }
    }
...


现在您可以同时更改TextColor和FontIcon。
希望有帮助!
如果你有任何问题,请告诉我。

相关问题