Reputation: 259
I want to have a time picker control where I can set hours, minutes and seconds. The default timepicker control does not have second included. What is the easiest way to have seconds value in timepicker control?
Upvotes: 2
Views: 1999
Reputation: 37633
(+ 1) Martin Zikmund
I would just to improve a bit the answer of Martin Zikmund.
TextBox Mask property has 3 build in variable characters
'a' which represents [a-Z] '9' which represents [0-9] '*' which represents a or 9
For 24 hours format:
XAML
<TextBox ui:TextBoxExtensions.CustomMask="0:[0-2],1:[0-9],5:[0-5]"
ui:TextBoxExtensions.Mask="01:59:59" x:Name="tbTime" TextChanged="tbTime_TextChanged"/>
Code
private void tbTime_TextChanged(object sender, TextChangedEventArgs e)
{
var textBox = (TextBox)sender;
string textBoxText = textBox.Text;
if (IsValidTimeFormat(textBoxText))
{
// Yep
}
else
{
// Nope
}
}
// Check if the string is valid TimeSpan
public bool IsValidTimeFormat(string input)
{
TimeSpan dummyOutput;
return TimeSpan.TryParse(input, out dummyOutput);
}
Explanation of ui:TextBoxExtensions.CustomMask="0:[0-2],1:[0-9],5:[0-5]" and ui:TextBoxExtensions.Mask="01:59:59"
0:[0-2] means that in any place we have insert 0 (zero) in ui:TextBoxExtensions.Mask="01:59:59" is allowed to input numbers 0-2.
In fact instead of 0 could be any char or number because it is like a variable name. So you can type like 3:[0-2] and use it here ui:TextBoxExtensions.Mask="31:59:59".
Upvotes: 0
Reputation: 39082
The built-in TimePicker
indeed does not support seconds input. You could subclass TimePicker
and manually extend it to support this scenario, but this might prove quite complex, because you would have to not only modify the template of the control itself, but you would have to edit the TimePickerFlyoutPresenter
to support seconds input. It may even not be possible at all, and may be an overkill.
I think the better and easier solution would be to use the TextBoxMask
extension which is part of the Windows Community Toolkit. This allows you to define a custom format of a TextBox
, which could look like this:
<TextBox extensions:TextBoxMask.CustomMask="5:[0-5]"
extensions:TextBoxMask.Mask="99:59:59" />
This TextBox
will support input in the format hh:mm:ss
. By default the Mask
supports characters a
for letters, 9
for digits 0-9 and *
for any character. You can define custom mask chars using CustomMask
which is what I did here to make sure the tens of minutes and seconds are limited to fifties (00-59).
Another solution could be to create a custom control that combines the normal built-in TimePicker
with a TextBox
just for seconds, but I think the TextBoxMask
is a better and user friendlier solution.
Upvotes: 4