s73v3r
s73v3r

Reputation: 1751

WPF Textbox use default text

I have a TextBox, which I want my users to enter a time value in the format XX:XX:XX. I already have validation in place to make sure they enter it in this format. However, now I'd like to have the colons there automatically. I'd like them to be in the textbox, and as the user types numbers, they just skip over the colons. Is it possible to have some kind of format decorator for the TextBox?

EDIT: I am using WPF 4.

Upvotes: 1

Views: 2521

Answers (3)

brunnerh
brunnerh

Reputation: 184296

Using three TextBoxes as Erno suggested is probably a better solution but you could also use the TextChanged event to add colons to the text (which might confuse the user), here'd be the code that would insert them after the second and fifth character:

private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
    TextBox tb = sender as TextBox;
    if (e.Changes.Count == 1)
    {
        if (e.Changes.ElementAt(0).AddedLength == 1 && (tb.Text.Length == 2 || tb.Text.Length == 5))
        {
            tb.Text += ":";
            tb.SelectionStart = tb.Text.Length;
        }
    }
}

Upvotes: 0

Emond
Emond

Reputation: 50672

If you want to stick to vanilla WPF you could create a Custom Control and add 3 textboxes.

Put colons in between them and handle the keydown events to pass focus from one textbox to the other and at the same time accepting numbers only.

Again: using the toolkit might be less work.

Upvotes: 0

JP.
JP.

Reputation: 5606

you can use a masked textbox from the wpf toolkit

http://wpftoolkit.codeplex.com/wikipage?title=MaskedTextBox&referringTitle=Home

Upvotes: 4

Related Questions