mercredi 6 mai 2015

WPF richtextbox treats string as a number of runs with the same formatting

I have a problem with WPF RichTextBox. I have a 'translation' application which has some text in the RichTextBox in the source language, which needs to be replaced by target language text. Additionally, I have a so called 'format painting' feature. This means that where the source text has specific formatting (font type, class, style attributes etc) the text in the rich text box is higlighted with a random color.

The translator can then apply this formatting to the target language text by selecting the text and clicking a respective color button. This works pretty well, because when I go through the text in text box, the content is split into runs wherever formatting is different.

The problem however happens, if the translator decides to amend only a bit of word - for example, source text is "Bubbles!". The translator wants to translate it as "Bulles!" - so he puts the cursor in the middle of the word, removes 'bb', adds 'l' and presses update. In such case, the rich text box treats this one word (where we have made no formatting changes) as three separate Inlines - 'Bu', 'l' and 'les'. As a result, the word is then treated as three separate words.

Can you advise any way to 'flatten' the text in the RTB so that when there's no highglight, text decorations or font size/color difference, it would treat text as a single inline?

The code I use for parsing the text:

     //the go through all paragraphs
                foreach (Paragraph paragraph in targetFlowDoc.Blocks)
                {
                    foreach (var inline in paragraph.Inlines)
                    {
                        var range = new TextRange(inline.ContentStart, inline.ContentEnd);
                        //get formatting for this fragment
                        Brush brush = (Brush)range.GetPropertyValue(TextElement.BackgroundProperty);
                        ClassAndStyle classAndStyle = TargetPage.GetClassAndStyleForBrush(brush);

                        TextDecorationCollection underline = (TextDecorationCollection)range.GetPropertyValue(Inline.TextDecorationsProperty);


                        //the fragment might contain more words
                        string[] words = range.Text.SplitIntoWords();

    //here, range.Text is split into three (Bu, l and les) which is wrong - I need all text with the same formatting treated as a single range (which I can then split into words)

                        for (int i = 0; i < words.Length; i++)
                        {
                           //stuff happens here to each word, not relevant, all good:)
                        }

Thanks for help!

Aucun commentaire:

Enregistrer un commentaire