C# 如何对字符串中的特定关键字进行预着色?
我有一份清单: 名字 年龄 描述 我需要在网格中显示 如何将描述的绑定属性显示到网格 如果一个描述包含一个特定的关键字“Good”,“Kind”,那么它必须以这样一种方式突出显示,“Good”必须是粉红色 “善良”必须是红色的 范例 姓名年龄描述 我是一个很好的人 我是一个非常善良的人 PQR 26我是一个快乐的人 我需要使用这个MVVM 型号:C# 如何对字符串中的特定关键字进行预着色?,c#,wpf,mvvm,model-binding,textblock,C#,Wpf,Mvvm,Model Binding,Textblock,我有一份清单: 名字 年龄 描述 我需要在网格中显示 如何将描述的绑定属性显示到网格 如果一个描述包含一个特定的关键字“Good”,“Kind”,那么它必须以这样一种方式突出显示,“Good”必须是粉红色 “善良”必须是红色的 范例 姓名年龄描述 我是一个很好的人 我是一个非常善良的人 PQR 26我是一个快乐的人 我需要使用这个MVVM 型号: private string name public string Name { get { return name } set { na
private string name
public string Name { get { return name } set { name = value; } }
private int age
public int Age{ get { return age} set { age= value; } }
private string description
public string Description{ get { return description} set { description= value; } }
在Xaml中:-
<TextBlock Name="tbDescription" Text="{Binding RowData.Row.Description, Mode=OneWay}"
Width="300" VerticalAlignment="Center" HorizontalAlignment="Left" TextTrimming="CharacterEllipsis" MinWidth="300">
您可以使用
值转换器
根据字符串返回所需的颜色
public class ForeGroundColorConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
var color = (string)value;
if(color.IndexOf("good", StringComparison.OrdinalIgnoreCase) >= 0)
{
// return 'Good' color.
}
else if (color.IndexOf("kind", StringComparison.OrdinalIgnoreCase) >= 0)
{
// return 'Kind' color.
}
// More cases.
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
然后在绑定中使用此转换器。(应用于您需要的控件。我使用TextBlock作为示例。)
首先将其添加到XML名称空间:
xmlns:converters="clr-namespace:<YourNameSpace>"
xmlns:converters=“clr命名空间:”
您还需要向窗口/控件添加资源
<Window.Resources>
<converters.ForeGroundColorConverter x:Key="ForeGroundColorConverter"/>
</Window.Resources>
特定关键字(例如“良好”颜色)是否只会更改。。。??使用这种逻辑..我不想整个句子改变颜色@burntotoast11我想检查它是否包含特定的关键字,仅突出显示wordUpdated答案,以使用.IndexOf
进行不区分大小写的搜索。我已在xaml中绑定:您需要使用答案中提供的绑定将前台
属性添加到您的文本块。我只想要粉色的“Good”关键字forecolor,黑色的描述的其余部分,然后
<Window.Resources>
<converters.ForeGroundColorConverter x:Key="ForeGroundColorConverter"/>
</Window.Resources>