1

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.

s73v3r
  • 1,751
  • 2
  • 22
  • 48

3 Answers3

4

you can use a masked textbox from the wpf toolkit

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

JP.
  • 5,536
  • 7
  • 58
  • 100
  • Looks good, but I'd prefer to stay with vanilla WPF if at all possible. I'm using WPF 4. – s73v3r Feb 11 '11 at 23:43
  • If you don't want to make use of the whole toolkit, although it is worth it because there are some great controls, you can access the source and pull out [just the control you need](http://wpftoolkit.codeplex.com/SourceControl/changeset/view/68480#1679740) – Tom Dudfield Feb 11 '11 at 23:57
  • 1
    I agree with @Tom Dudfield. There's a ton of nice stuff in there. You're not going to find the functionality baked into WPF, and you'll most likely end up doing exactly what the toolkit is doing (deriving from the default textbox and rolling your own) but with no gain... – JP. Feb 12 '11 at 05:24
0

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.

Emond
  • 50,210
  • 11
  • 84
  • 115
0

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;
        }
    }
}
H.B.
  • 166,899
  • 29
  • 327
  • 400