首页 > 解决方案 > 在本机 UWP 中,如何为字符串中的特定字符应用颜色或如何在文本框控件中显示多色文本

问题描述

我的要求是我喜欢在文本框控件中显示一些字符串,并且我想为字符串中的特定字符应用颜色。例如,在下图中,我的输入字符串是“我的标签”,并且我将文本颜色设置为“蓝色”。现在我需要以不同颜色显示特定字符​​或字符串,例如下图中的“我的”字符串。请给我一个可能的建议来实现我的要求。

在此处输入图像描述

标签: c#xamluwptextboxxamarin.uwp

解决方案


文本块

一个更简单的方法是Span在你的内容中使用标签TextBlock,这要归功于 XAML 的美感。请参阅以下内容:

<TextBlock Foreground="Red" FontSize="25">
    I'M RED BY DEFAULT <Span Foreground="Blue">BUT NOW I'M BLUE!</Span>
</TextBlock>

跨度标签结果

文本框

如果满足某个条件(即输入了字符“!”),您可以使用转换器更改文本框内容的前景色,但这将更改整个内容的前景色,而不仅仅是字符“!”

我认为这不符合您的要求,但无论如何我都会发布一些代码,以防万一它可以帮助您找到解决方案。

转换器。

public class CharColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {

        String ValueContent = String.Empty;

        String ForegroundColor = "#000000";

        String charValue = "!";

        //check if value is null

        if (value != null)
        {                
            ValueContent = (String)value;
            // Check for the char ! and change foreground colour 
            if (ValueContent.Contains(charValue)
            {
                ForegroundColor = "#e40034";
            }
        }

        return ForegroundColor;
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

XAML

<TextBox Foreground="{Binding TextValue,Converter={StaticResource CharColorConverter}}" Text="{Binding TextValue}" />

推荐阅读