编辑 RichTextBox Run 元素而不拆分为多个 Run 元素 [英] Edit RichTextBox Run element without splitting into multiple Run elements

查看:72
本文介绍了编辑 RichTextBox Run 元素而不拆分为多个 Run 元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 RichTextBox 的 WPF 应用程序.文本框中的文本由跨度以编程方式构建并运行到一个段落.每个句子都是一个Span.句子中的每个单词都是一个Run.用户可以编辑文本.

I have a WPF application with a RichTextBox. The text in the textbox is built up programmatically by spans and runs to a paragraph. Each sentence is a Span. Each word in a sentence is a Run. The user can edit the text.

RichTextBox 看起来像这样

The RichTextBox looks like this

<RichTextBox x:Name="txtRichSpeech">
    <FlowDocument x:Name="txtRichSpeechDoc">
        <Paragraph x:Name="txtRichSpeechContent"></Paragraph>
    </FlowDocument>
</RichTextBox>

文本这只是一个测试文本."将有结构

The text "This is just a test text." will have the structure

<Span>
    <Run>This</Run>
    <Run> </Run>
    <Run>is</Run>
    <Run> </Run>
    <Run>just</Run>
    <Run> </Run>
    <Run>a</Run>
    <Run> </Run>
    <Run>test</Run>
    <Run> </Run>
    <Run>text.</Run>
</Span>

当用户编辑例如单词test"时通过在中间添加一个 E 我希望 test 成为 teEst但我得到了以下结构:

When the user edits for example the word "test" by adding an E in the middle I want <Run>test</Run> to become <Run>teEst</Run> but instead I get the following structure:

<Span>
    <Run>This</Run>
    <Run> </Run>
    <Run>is</Run>
    <Run> </Run>
    <Run>just</Run>
    <Run> </Run>
    <Run>a</Run>
    <Run> </Run>
    <Run>te</Run>
</Span>
<Run>E</Run>
<Span>
    <Run>st</Run>
    <Run> </Run>
    <Run>text.</Run>
</Span>

我怎样才能防止这种行为并且只使用 teEst?

How can I prevent this behavior and just have <Run>teEst</Run>?

推荐答案

Paste() 方法用于将剪贴板的内容粘贴到 RichTextBox.要防止这种行为,请使用 InsertTextInRun() 方法:

This behavior is happening when the Paste() method used to paste the contents of the Clipboard in the RichTextBox. To prevent this behavior use the InsertTextInRun() method:

txtRichSpeech.CaretPosition.InsertTextInRun(Clipboard.GetText()); 

将在当前插入符号位置插入文本.仅当插入符号不在 Run 元素范围内时,Run 将与文本数据一起插入.

A text will be inserted at the current caret position. Only if the caret is not scoped by a Run element, a Run will be inserted along with the text data.

编辑

此行为的另一个原因是 RichTextBox 控件和当前输入语言的语言不同.将 RichTextBoxLanguage 属性设置为当前语言环境(输入语言)的语言即可解决问题.瑞典语示例:

Another cause of this behavior is different language of the RichTextBox control and the current input language. Setting the Language property of the RichTextBox to the language of the current locale (input language) solves the problem. Example for Swedish:

<RichTextBox x:Name="txtRichSpeech" Language="sv-SE">
</RichTextBox>

这篇关于编辑 RichTextBox Run 元素而不拆分为多个 Run 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆