问题描述
我正在尝试使用UWP中的RichEditBox构建“令牌化” URL文本框。本质上,我想要一个如下所示的URL栏:
此图片来自https://regexr.com/。请注意,与其他字符相比,用方括号括起来的子字符串具有特定的格式。这正是我要实现的功能,但是我似乎无法弄清楚如何在RichEditBox中实现它。
我尝试过的事情:
- 使用正则表达式查找不同的子字符串,但是我不知道如何在RichEditBox中找到这些子字符串的索引位置。似乎没有可用的
Find
或IndexOf
方法。 - 我还尝试在每次引发TextChanged事件时更新文本格式。但是,我为此感到困惑,因为您需要了解其他字符才能确定是否应格式化子字符串。管理此状态信息很麻烦,因为当您一次开始删除或添加多个字符时,事情变得很奇怪。
private void RichEdditBox_TextChanged(object sender,RoutedEventArgs e)
{
if (sender is RichEditBox r)
{
string oldText = _text;
r.Document.GetText(TextGetoptions.None,out string newText);
if (oldText == newText) return;
int
textLength = newText.Length,selectionLength = r.Document.Selection.Length,selectionStart = r.Document.Selection.StartPosition;
var currentStart = selectionStart - 2;
bool isEnd = false;
if (Math.Abs(textLength - oldText?.Length ?? 0) > 1)
{
ReformatandReset(r);
}
else if (currentStart >= 0 && newText[selectionStart - 1] == '{' && newText[currentStart] == '{')
{
if (!_startList.Contains(currentStart)) _startList.Add(currentStart);
}
else if (currentStart >= 0 && newText[selectionStart - 1] == '}' && newText[currentStart] == '}')
{
isEnd = true;
if (!_endList.Contains(currentStart)) _endList.Add(currentStart);
}
if (isEnd)
{
var prevIoUsEnd = _endList.Where(x => x < currentStart).DefaultIfEmpty(-1).Max();
// find the max start < end
var matchingStart = _startList.Where(x => x < currentStart && x > prevIoUsEnd).DefaultIfEmpty(-1).Max();
Highlight(r,matchingStart,currentStart + 2);
}
_text = newText;
}
}
private void ReformatandReset(RichEditBox r)
{
_startList.Clear();
_endList.Clear();
r.Document.GetText(TextGetoptions.None,out string text);
var range = r.Document.GetRange(0,text.Length - 1);
range.CharacterFormat.BackgroundColor = Windows.UI.Colors.Transparent;
r.Document.ApplydisplayUpdates();
var startIndex = text.IndexOf("{{",0);
var endindex = text.IndexOf("}}",0);
while (startIndex > -1 || endindex > -1)
{
if (startIndex > -1 && endindex > -1 && endindex > startIndex + 2)
{
Highlight(r,startIndex,endindex + 2);
}
if (startIndex > -1)
{
_startList.Add(startIndex);
startIndex = text.IndexOf("{{",startIndex + 1);
}
if (endindex > -1)
{
_endList.Add(endindex);
endindex = text.IndexOf("}}",endindex + 1);
}
}
}
private void Highlight(RichEditBox r,int start,int end)
{
if (start < 0 || end < 0) return;
var range = r.Document.GetRange(start,end);
range.CharacterFormat.BackgroundColor = Windows.UI.Colors.LightBlue;
r.Document.ApplydisplayUpdates();
}
private List<int> _startList = new List<int>();
private List<int> _endList = new List<int>();
private string _text;
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)