c# - 在本机 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}" />
推荐阅读
- javascript - 在页面加载时自动打开 React JS 应用程序中的模态
- node.js - tsc 的 bash 命令返回未找到
- java - java - 如何在命令行java中的-DconfigFile中有多个值?
- php - PHP - 构建前 k 个项目的排序列表
- c++ - 创建一个数组以允许存储用户输入并稍后在代码中使用
- java - 如何在所有 Android 设备上完美检测抖动水平?
- html - 如何使用 css 透视来匹配 div 以在视觉上适合 svg 笔记本电脑屏幕?
- python - mypy vs mypy-lang vs pyls-mypy python包之间的区别
- oracle - 如何从透视的 Oracle 表中删除一列?
- r - R如何用2个向量处理ifelse中的NA?