当用户在richtextbox中输入时,使用WPF可以自动替换单词
本文关键字:WPF 单词 替换 使用 用户 richtextbox 输入 | 更新日期: 2023-09-27 18:14:22
public void overallTextReplace(RichTextBox[] rtb) {
string[] keyword = { "FCI", "CNG", "DCR", "EZR", "VASC", "CND" };
string[] newString = { "Forecourt Controller","Case Number Declined" ,"Case Number Given", "Dispenser Card reader", "Enhanced Zone Router", "Verifone Authorized Service Contractor" };
TextRange[] text = new TextRange[rtb.Length];
for (int I = 0; I < rtb.Length; I++) {
text[I] = new TextRange(rtb[I].Document.ContentStart, rtb[I].Document.ContentEnd);
}
for (int I = 0; I < text.Length; I++) {
for (int K = 0; K < keyword.Length; K++) {
TextPointer current = text[I].Start.GetInsertionPosition(LogicalDirection.Forward);
string textInRun = current.GetTextInRun(LogicalDirection.Forward);
if (!string.IsNullOrEmpty(textInRun)) {
int index = textInRun.IndexOf(keyword[K]);
if (index != -1) {
TextPointer selectionStart = current.GetPositionAtOffset(index, LogicalDirection.Forward);
TextPointer selectionEnd = selectionStart.GetPositionAtOffset(keyword.Length, LogicalDirection.Forward);
TextRange selection = new TextRange(selectionStart, selectionEnd);
selection.Text = newString[K];
selection.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Regular);
rtb[I].Selection.Select(selection.Start, selection.End);
rtb[I].Focus();
}
}
current = current.GetNextInsertionPosition(LogicalDirection.Forward);
}
}
}
好的,所以这段代码将在传递给函数时查看WPF表单中的所有richtextbox,然后查找列出的关键字并将其替换为newString。我的问题是,程序只看一行文本从开始到结束。如果它检测到换行,它将不会越过它,例如:line1: FCI是一个燃料控制器。它可以很好地替换它,但如果我在第2行有更多,它就不会进行替换。如果它有任何区别,他们有6个richtextbox被传递给这个函数。
刚刚发现了一个错误,但它与我的第一个问题无关。因此,似乎有6个数组索引阻止代码运行,并抛出一个空ref上的TextRange选择=新的TextRange (selectionStart, selectionEnd);但如果我用VASC作为要替换的词,他们也不例外。我不知道为什么。
对于winforms:试试这个(虽然我没有运行这段代码,但逻辑上它应该工作):
public void overallTextReplace(RichTextBox[] rtb)
{
string[] keyword = { "FCI", "CNG", "DCR", "EZR", "VASC", "CND" };
string[] newString = { "Forecourt Controller","Case Number Declined" ,"Case Number Given", "Dispenser Card reader", "Enhanced Zone Router", "Verifone Authorized Service Contractor" };
for (int i = 0; i < rtb.Length; i++)
{
for (int j = 0; j < 6; j++)
{
rtb[i].Rtf=rtb[i].Rtf.Replace(keyword[j],newString[j]);
}
}
}
为wpf: for (int i = 0; i < rtb.Length; i++)
{
RichTextBox rtb_wording= rtb[i];
var textRange = new TextRange(rtb_wording.Document.ContentStart, rtb_wording.Document.ContentEnd);
string rtf;
using (var memoryStream = new MemoryStream())
{
textRange.Save(memoryStream, DataFormats.Rtf);
rtf = ASCIIEncoding.Default.GetString(memoryStream.ToArray());
}
for (int j = 0; j < 6; j++)
{
rtf =rtf.Replace(keyword[j],newString[j]);
}
MemoryStream stream = new MemoryStream (ASCIIEncoding.Default.GetBytes(rtf));
rtb_wording.SelectAll();
rtb_wording.Selection.Load(stream, DataFormats.Rtf);
}