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

Why RichTextBox Cursor jumps when using TextPointer.GetOffsetToPosition and TextPointer.GetPositionAtOffset to restore cursor position

$
0
0

Hi,

In a WPF test app, I tried to uppercase all text in the RichTextBox in its TextChanged event handler, using the code below. In the TextChanged event handler, I first save the cursor position, and then uppercase all text in the RichTextBox, finally I restore the cursor position.

Under "EN English (United States)" keyboard layout, it is working fine, but if I switch to another keyboard layout, such as "EN English (United States)" keyboard layout, the cursor will jump forward when I type something into the middle of the text.

Could anyone help to explain to me why it is not working?

xaml

<Window x:Class="UKKeyboardTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="195" Width="491"><Grid><RichTextBox Height="51" HorizontalAlignment="Left" Margin="57,27,0,0" Name="richTextBox1" VerticalAlignment="Top" Width="335" /></Grid></Window>

code behind

namespace UKKeyboardTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        bool _ignoreChanges = false;

        public MainWindow()
        {
            InitializeComponent();
            Paragraph p = new Paragraph();
            p.Inlines.Add(new Run("sample text <<type some text here>> sample text"));
            richTextBox1.Document = new FlowDocument(p);

            richTextBox1.TextChanged += new TextChangedEventHandler(richTextBox1_TextChanged);
        }


        private void richTextBox1_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (_ignoreChanges) return;

            int caretPosition = richTextBox1.Document.ContentStart.GetOffsetToPosition(richTextBox1.CaretPosition);

            _ignoreChanges = true;
            richTextBox1.SelectAll();
            richTextBox1.Selection.Text = richTextBox1.Selection.Text.ToUpper();
            _ignoreChanges = false;

            richTextBox1.CaretPosition = richTextBox1.Document.ContentStart.GetPositionAtOffset(caretPosition);
        }
    }
}




Viewing all articles
Browse latest Browse all 18858

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>