Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

Programmatically Set CaretPosition to a specific Inline inside a FlowDocument of a RichTextBox

$
0
0

I have a RichTextBox that contains both Text and Pictures.  I've done this using Run's and InLineUIContainer's.  I also have some buttons that will programmatically insert any number of Runs, InlineUIContainers, and Paragraphcs to the FlowDocument at the current CaretPosition.  The problem is that the CaretPosition reacts very spiratically after I insert this content programmatically.  All I want to do is have the CarretPosition set to the end of the new content I put in.  

Is there a way to get a TextPointer for the location after this new content?  I have a handle on the actual Inline that the CaretPosition has to be set for, but I don't know how to get a TextPointer there.  

The only solution I've come up with is to determine a 'Location #' of the cursor prior to inserting the content: 


        private int GetTextPointerLocation(TextPointer pPointer)
        { 
            int iLocation = -1; 

            try
            { 

                TextPointer pCurrent = this.Document.ContentStart;
                while (pCurrent != null)
                { 
                    if (pCurrent.CompareTo(pPointer) == 0)
                        break; 
                    iLocation++;
                    pCurrent = pCurrent.GetNextInsertionPosition(LogicalDirection.Forward); 
                } 
            }
            catch (Exception ex)
            { 
            } 

            return iLocation;
        }

The problem is that this is extremely slow (multiple seconds for a small amount of text - GetNextInsertionPosition is what takes all the time).

After that I get the TextPointer via this method:

public TextPointer GetTextPointerForLocation(int iLocation)
        {
            TextPointer tpReturn = this.Document.ContentStart;
            try
            {
                int iCurLocation = 0;
                while (tpReturn != null)
                {
                    if (iLocation == iCurLocation)
                        return tpReturn;
                    iCurLocation++;
                    tpReturn = tpReturn.GetNextInsertionPosition(LogicalDirection.Forward);
                }
            }
            catch (Exception ex)
            { 
            }

            return tpReturn;
        }

Which I can then use to set the CaretPosition.  The performance is just way to slow.  There has to be a faster way to set the CaretPosition to a location in reference to an Inline, or even a Paragraph.

Basically what I need, is a method that I can pass in an Inline that's inside the FlowDocument, and have it return a TextPointer at the beginning of that Inline.  

Thanks for the help!


Viewing all articles
Browse latest Browse all 18858

Trending Articles