using System.Globalization;
using System.Text.RegularExpressions;
using System.Windows.Data;
using System.Windows.Documents;
namespace Melskin.Converters.Internal;
///
/// StringToCodeConverter 类实现了 IValueConverter 接口,用于将字符串转换为具有代码样式的 RichTextBox 控件。该类提供了一个静态实例 Instance,用于在 XAML 中方便地引用。
/// 通过 Convert 方法,可以将输入的字符串转换为富文本格式,并且会对字符串中的特殊字符(如引号、尖括号等)进行高亮显示。ConvertBack 方法返回 DependencyProperty.UnsetValue,表示不支持反向转换。
///
internal class StringToCodeConverter : IValueConverter
{
//显式静态构造函数告诉c#编译器
//不将type标记为beforefieldinit
static StringToCodeConverter()
{
}
private StringToCodeConverter()
{
}
///
///
///
public static StringToCodeConverter Instance { get; } = new();
///
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;
}
///
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}