BenW301
BenW301

Reputation: 382

Programatically enable RichTextBox and show caret

For the application that I am currently working on, I have a usercontrol that is added to the form programatically several times. Part of the usercontrol is a RichTextBox that is set to transparent and has the click functionality disabled so that it acts more like a label and blends into the user control.

When the user control is deliberately clicked by the user, the RichTextBox's background is changed to white, IsReadOnly is set to False, and clicking is enabled.

The problem I am trying to correct is that the user still has to click on the RichTextBox a second time to enable the caret prior to typing. All my Googling and code attempts to programatically set the caret haven't worked. Any suggestions as to why the below code isn't working? Is there anything else I need to do?

 contentBox.IsHitTestVisible = true;
 contentBox.Background = new SolidColorBrush(Color.FromRgb(240, 240, 240));
 contentBox.IsReadOnly = false;
 //manage caret position
 TextPointer newPointer = contentBox.CaretPosition;
 newPointer = newPointer.DocumentEnd;
 contentBox.CaretPosition = newPointer;

Upvotes: 1

Views: 204

Answers (1)

Frank J
Frank J

Reputation: 1696

I think what you are missing is setting the logical and keyboard focus to your control afterwards. Try

Dispatcher.BeginInvoke(
    new Action(delegate()
    {
        contentBox.Focus();         // Set Logical Focus
        System.Windows.Input.Keyboard.Focus(contentBox); // Set Keyboard Focus
    })
);

Upvotes: 1

Related Questions