gpt4 book ai didi

c# - 如何在 WPF RichTextBox 中突出显示数字

转载 作者:太空宇宙 更新时间:2023-11-03 14:54:32 25 4
gpt4 key购买 nike

我正在尝试将 WPF RichTextBox 中的所有数字重新着色为不同的颜色。我一直在关注this tutorial ,但我发现文本中的字母几乎是随机突出显示的。这是我目前拥有的处理程序:

private void DescriptionText_TextChanged(object sender, TextChangedEventArgs e)
{
var range = new TextRange(DescriptionText.Document.ContentStart, DescriptionText.Document.ContentEnd);
var regex = new Regex("[0-9]+");
var num_ranges = new List<TextRange>();

// add all the ranges with numbers
foreach (Match match in num_reg.Matches(range.Text))
{
var start = range.Start.GetPositionAtOffset(match.Index);
var end = range.Start.GetPositionAtOffset(match.Index + match.Length);

num_ranges.Add(new TextRange(start, end));
}

// unsuscribe before making changes
DescriptionText.TextChanged -= this.DescriptionText_TextChanged;

range.ClearAllProperties();
range.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Black));

foreach (var r in num_ranges)
{
r.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Red));
}

DescriptionText.TextChanged += this.DescriptionText_TextChanged;
}

最佳答案

试试这个

DescriptionText.TextChanged -= this.DescriptionText_TextChanged;
var regExp = new Regex(@"^-*[0-9,\.]+$");
foreach (Match match in regExp.Matches(rtb.Text))
{
var textRange = rtb.Selection;
textRange.Select(match.Index, match.Length);
textRange.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Red));
//rtb.SelectionColor = Color.Red;
}
DescriptionText.TextChanged += this.DescriptionText_TextChanged;

关于c# - 如何在 WPF RichTextBox 中突出显示数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50278754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com