RichTextBox and Inserting at Caret Positions

爷,独闯天下 提交于 2019-12-01 17:21:26

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...

Dror

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 :)

XSapien

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?

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!