RichTextBox and Inserting at Caret Positions

后端 未结 3 1189
感动是毒
感动是毒 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...

提交回复
热议问题