好的,我有一个使用Richtextbox继承的类。
我需要从RichTextBox中获取选定的文本,并将其替换为一些标记,我的意思是:
A sample text to replace but only the selected sample word然后选择"sample“并单击按钮将其转换为:
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中的所有文本?
发布于 2011-05-04 22:02:14
一种方法是从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);
}发布于 2011-05-04 19:14:00
试试这个:
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);
}https://stackoverflow.com/questions/5888545
复制相似问题