好的,我有一个使用Richtextbox继承的类。
我需要从RichTextBox中获取所选文本并将其替换为某些标记,我的意思是:
A sample text to replace but only the selected sample word
我选择“示例”并单击按钮将其转换为:
A <A>sample</A> text to replace but only the selected sample word
我一直在使用的替换代码是:
string selected = this.Selection.Text.Trim();
if (selected.Length > 0)
{
this.Html = this.FormatedText.Replace(selected, string.Format("<{0}>{1}</{0}>", tagName, selected));
}
Html和FormatedText是我班级的属性
问题是RichTextBox.selection.text获取样本,如果我尝试使用string.replace,则会标记所有样本单词,而不仅仅是所选单词。
¿如何在原始文本中获取所选单词和所选单词的初始位置,然后使用新插入内容获取RichTextBox中的所有文本?
答案 0 :(得分:0)
试试这个:
private void button1_Click(object sender, RoutedEventArgs e)
{
rtb.Selection.Text = "<A>" + rtb.Selection.Text + "</A>";
}
rtb是RichTextBox
编辑:
希望这就是你想要的......现在你得到所有改变的项目
rtb.Selection.Text = "<A>" + rtb.Selection.Text + "</A>";
//this works in silverlight
rtb.SelectAll();
string all = rtb.Selection.Text;
List<string> allThatChanged = new List<string>();
while (all.Contains("<A>"))
{
allThatChanged.Add(all.Substring(all.IndexOf("<A>"), all.IndexOf("</A>") - all.IndexOf("<A>") + 4));
all = all.Remove(all.IndexOf("<A>"), all.IndexOf("</A>") - all.IndexOf("<A>") + 4);
}
答案 1 :(得分:0)
一种方法是从richtextbox中的内容开头选择到所选文本的开头,然后选择文本和.lenght :):
string selected = this.Selection.Text;
if (selected.Length > 0)
{
selected = selected.Trim();
//Change the selection from the start of the full text to the start of the selection text
this.Selection.Select(this.ContentStart, this.Selection.Start);
string init = this.FormatedText.Substring(0, this.Selection.Text.Length);
string final = this.FormatedText.Substring(this.Selection.Text.Length + selected.Length, this.FormatedText.Length - (this.Selection.Text.Length + selected.Length));
this.Html = string.Format("{0}{1}{2}", init, string.Format("<{0}>{1}</{0}>", tagName, selected), final);
}