Reputation: 349
I'm developing an WPF application and I got two datepicks input where use can select the date, But I am having some problem with these inputs cause the user can write whatever they want on it as in the image bellow
Is there some way to mask this inputs ? as dd/mm/yyy to only allow users to write dates and it automatically inserts the / slash ?
I tried follow this example but didn't work as it only formate the date after the user choose it from the calendar
I know that there are some "masked inputs" but they don't work with datepicker input
Thanks in Advance.
EDIT
here is my xaml code
<Border Grid.Column="0" Grid.Row="1" Margin="10 0 0 0" Style="{StaticResource InputBorder}" Height="30" VerticalAlignment="Top">
<DatePicker x:Name="EDT_DATA_INICIAL"></DatePicker>
</Border>
<Border Grid.Column="1" Grid.Row="1" Margin="10 0 10 0" Style="{StaticResource InputBorder}" Height="30" VerticalAlignment="Top">
<DatePicker x:Name="EDT_DATA_FINAL"></DatePicker>
</Border>
Upvotes: 1
Views: 3255
Reputation: 349
Just complementing the @Tronald's answer I'am using his event PreviewTextInput
and I complementend it using this code in a keyUp event
private void SetDateFormat(object sender, KeyEventArgs e)
{
DatePicker dt = (DatePicker)sender;
string justNumbers = new String(dt.Text.Where(Char.IsDigit).ToArray());
if (justNumbers.Length == 8)
{
string newDate = justNumbers.Insert(2, "/").Insert(5, "/");
try
{
dt.SelectedDate = DateTime.Parse(newDate);
}catch(Exception ex)
{
dt.text = "";
}
}
}
That format the date when use only digite numbers or ex : 18061993 > 18/06/1993 and when the date is incorrect it clears the input preventing errors
Upvotes: 3
Reputation: 1585
Create a PreviewTextInput
event in your DatePicker and handle the logic in there. The below example will restrict input to numbers and "/" only. You will have to figure out how to automatically input the "/" on your own if you wish to do that.
Maybe loop through each character of the string as it's built and determine if you need to add the "/" at a certain point. You can e.Handled = true
to block the user input then set the DatePicker.Text
as required. This should be enough to get you started.
private void DatePicker_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
DatePicker dp = (DatePicker)sender;
Regex regex = new Regex("[^0-9/]"); //regex that matches allowed text
e.Handled = regex.IsMatch(e.Text);
}
Regex reference isSystem.Text.RegularExpressions
Upvotes: 1