首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >RichTextBox Silverlight选择的文本替换

RichTextBox Silverlight选择的文本替换
EN

Stack Overflow用户
提问于 2011-05-04 19:02:21
回答 2查看 1.4K关注 0票数 0

好的,我有一个使用Richtextbox继承的类。

  • INPUT:

我需要从RichTextBox中获取选定的文本,并将其替换为一些标记,我的意思是:

代码语言:javascript
复制
A sample text to replace but only the selected sample word

然后选择"sample“并单击按钮将其转换为:

代码语言:javascript
复制
A <A>sample</A> text to replace but only the selected sample word

我一直使用的替换代码是:

代码语言:javascript
复制
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,所有示例单词都将被标记,而不仅仅是选定的一个。

  • NEEDS:

如何获得所选单词和所选单词在原始文本中的初始位置,然后使用新插入获得我的RichTextBox中的所有文本?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-05-04 22:02:14

一种方法是从richtextbox中的内容开始选择到所选文本的开头,然后获取所选文本并将其.lenght到它:):

代码语言:javascript
复制
 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);
            }
票数 0
EN

Stack Overflow用户

发布于 2011-05-04 19:14:00

试试这个:

代码语言:javascript
复制
 private void button1_Click(object sender, RoutedEventArgs e)
    {
        rtb.Selection.Text = "<A>" + rtb.Selection.Text + "</A>";
    }

rtb是RichTextBox

编辑:

希望这是你想要的。现在你得到了所有改变的物品

代码语言:javascript
复制
        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);
        }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5888545

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档