RichTextBox and Inserting at Caret Positions

后端 未结 3 1163
感动是毒
感动是毒 2021-01-18 15:29

Here is the deal: I have a RichTextBox control and it works fine. The problem is that there is a button \"Insert Current DateTime\" which adds/injects the current datetime i

相关标签:
3条回答
  • 2021-01-18 15:47

    I'm using this code to successfully do what you are attempting:

    private void insertNowButton_Click(object sender, RoutedEventArgs e)
    {
        //NOTE:  The caret position does not change.
        richTextBox1.CaretPosition.InsertTextInRun(DateTime.Now.ToString());
    }
    

    EDIT: Addressing Update 1

    private void DateTimeStampButton_Click(object sender, RoutedEventArgs e)
    {
        var tr = new TextRange(textBox.Document.ContentStart, textBox.Document.ContentEnd);
    
        if (tr.Text.Length == 2)
        {
            if (tr.Text == "\r\n")
            {
                tr.Text = tr.Text.TrimStart(new[] { '\r', '\n' });
            }
        }
    
        /* Changing the text is the only way I can get the date to insert at the beginning */
        tr.Text = "I need a beer at ";
    
        textBox.CaretPosition.InsertTextInRun(DateTime.Now.ToString());
    }
    

    It looks like SetValue is changing the text so based on my test that actually changing the text resets the caret, I would agree with you that SetValue is causing the problem...

    0 讨论(0)
  • 2021-01-18 15:52

    This worked for me:

    private void InsertText(String text, RichTextBox rtb)
    {
        rtb.CaretPosition = rtb.CaretPosition.GetPositionAtOffset(0, LogicalDirection.Forward);
        rtb.CaretPosition.InsertTextInRun(text);
    }
    

    I found the code here:

    How do I move the caret a certain number of positions in a WPF RichTextBox?

    0 讨论(0)
  • 2021-01-18 16:08

    I tried this solution with WPFToolkit.Extended RichTextBox and it didn't work for me. However I found another one and thought it would be good to post it in here in case someone else could use it.

    My problem was also that the after I clicked a button that is supposed to append text at the caret location, it instead adds it at the beginning of the RichTextBox.

    So The solution I found is similar to the one in here -

    RichTextBox CaretPosition physical location

    Instead of using CaretPosition I used RichTextBox.Selection.Start.InsertTextInRun("SomeText").

    It considered the selection's start as the caret position even though no selection was made and therefore was good enough for me.

    I hope someone will find this useful :)

    0 讨论(0)
提交回复
热议问题