Files
Shrlalgo.RvKits/Melskin/Converters/Internal/StringToCodeConverter.cs
2026-02-17 22:17:13 +08:00

73 lines
2.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Globalization;
using System.Text.RegularExpressions;
using System.Windows.Data;
using System.Windows.Documents;
namespace Melskin.Converters.Internal;
/// <summary>
/// StringToCodeConverter 类实现了 IValueConverter 接口,用于将字符串转换为具有代码样式的 RichTextBox 控件。该类提供了一个静态实例 Instance用于在 XAML 中方便地引用。
/// 通过 Convert 方法可以将输入的字符串转换为富文本格式并且会对字符串中的特殊字符如引号、尖括号等进行高亮显示。ConvertBack 方法返回 DependencyProperty.UnsetValue表示不支持反向转换。
/// </summary>
internal class StringToCodeConverter : IValueConverter
{
//显式静态构造函数告诉c#编译器
//不将type标记为beforefieldinit
static StringToCodeConverter()
{
}
private StringToCodeConverter()
{
}
/// <summary>
///
/// </summary>
public static StringToCodeConverter Instance { get; } = new();
/// <inheritdoc />
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
var str = value as string;
var textBox = new RichTextBox()
{
IsReadOnly = true,
FontSize = 12,
Foreground = Brushes.Red,
BorderThickness = new Thickness(0),
};
if (string.IsNullOrEmpty(str)) return textBox;
const string pattern = "=\".*?\"|[</>]";
var index = 0;
var document = new FlowDocument();
var paragraph = new Paragraph();
var inlines = paragraph.Inlines;
str = str?.Replace(@"\n", Environment.NewLine).Replace(@"\t", "\t");
if (str != null)
{
foreach (Match match in Regex.Matches(str, pattern))
{
inlines.Add(str.Substring(index, match.Index - index));
inlines.Add(new Run(match.Value) { Foreground = Brushes.Blue });
index = match.Index + match.Length;
}
inlines.Add(str.Substring(index));
}
document.Blocks.Add(paragraph);
textBox.Document = document;
return textBox;
}
/// <inheritdoc />
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}