Search code examples
wpfwpftoolkitmaskedtextbox

WPF: MaskedTextBox + SetCaret


So I am currently using the WPF Extended Toolkit with the MaskedTextBox and have the mask set up as:
(000) 000-000
which is the format for a phone number.

I have a problem that if the user selects the textbox with a mouse click the caret goes to the position where the cursor was (unless the cursor is beyond the scope of the mask then the caret defaults to the end.

If I tab into the textbox it sets the caret to right after the opening parenthesis which is what I'm looking for but it does not behave the same way with a mouse click.

I have tried the following:

Tried overriding in the actual toolkit file like this with mousedown, mouseup, ongotfocus and such.

protected override void OnMouseDown(MouseButtonEventArgs e)
{
    this.Select(1,0);
    base.OnMouseDown(e);
}

Tried to also set events on the actual MaskedTextBox itself with the code behind.

I've searched all over the internet and still nothing.


Solution

  • This should work for you; in the markup:

    <xctk:MaskedTextBox x:Name="MyMaskedTextBox"  Mask="(000) 000-000" PreviewMouseDown="MyMaskedTextBox_PreviewMouseDown"></xctk:MaskedTextBox>
    

    And the event handler:

    private void MyMaskedTextBox_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        MyMaskedTextBox.Focus();
        MyMaskedTextBox.Select(1, 0);
        e.Handled = true;            
    }