Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add dots automatically while writing in TextBox

Tags:

c#

wpf

xaml

I have one TextBox with binding on DateTime type. I need to get a dot after first 2 chars and second 2 chars, for example: 12.12.1990. I'm using behavior in TextChanged event, that code:

void tb_TextChanged(object sender, TextChangedEventArgs e)
{
    int i = tb.SelectionStart;
    if (i == 2 || i == 5)
    {                
        tb.Text += ".";
        tb.SelectionStart = i + 1;
    }
}

That is working, but if I want to delete text by backspace, obviously I can't delete dots, because event is called again.

What is better way to solve it?

Solved

It works But if you can, you may fix my algorithm.

        public string oldText = "";
        public string currText = "";
        private void TextBox1_TextChanged(object sender, TextChangedEventArgs e)
        {
            oldText = currText;
            currText = TextBox1.Text;
            if (oldText.Length > currText.Length)
            {
                oldText = currText;
                return;
            }
            if (TextBox1.Text.Length == currText.Length)
            {
                if (TextBox1.SelectionStart == 2 || TextBox1.SelectionStart == 5)
                {
                    TextBox1.Text += ".";
                    TextBox1.SelectionStart = TextBox1.Text.Length;
                }
            }

        }
like image 328
Tim Smirnov Avatar asked Nov 02 '22 01:11

Tim Smirnov


2 Answers

I would do it in the KeyPress event, so you can filter by what kind of key it was (using the KeyChar argument with Char.IsLetter() and similar functions).

Also, add the dot when the next key is pressed. If the user has typed "12", don't add a dot yet. When the user presses 1 to add the second "12", add it then (before the new character).

like image 182
George T Avatar answered Nov 14 '22 04:11

George T


Use String Format in the xaml control like so

StringFormat='{}{0:dd.MM.yyyy}'

I just tested it and this will even convert slashes to the dots.

For example

<TextBox.Text>
 <Binding Path="Person.DateOfBirth" UpdateSourceTrigger="LostFocus" StringFormat='{}{0:dd.MM.yyyy}'></Binding>
</TextBox.Text>

If you are using a datepicker then you will need to override its textbox template as in the link below with the String Format above.

This link may help if if you are trying to apply it to a datepicker.

like image 27
kenjara Avatar answered Nov 14 '22 06:11

kenjara