-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTimeInputBehavior.cs
More file actions
43 lines (38 loc) · 1.27 KB
/
Copy pathTimeInputBehavior.cs
File metadata and controls
43 lines (38 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using System;
using System.Globalization;
using System.Windows.Controls;
using Microsoft.Xaml.Behaviors;
namespace Jon.Wpf.CustomControls
{
public class TimeInputBehavior : Behavior<TextBox>
{
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.LostFocus += OnLostFocus;
}
protected override void OnDetaching()
{
base.OnDetaching();
this.AssociatedObject.LostFocus -= OnLostFocus;
}
private void OnLostFocus(object sender, System.Windows.RoutedEventArgs e)
{
// Validate and reformat the time when the control loses focus
string text = this.AssociatedObject.Text.Trim();
// If no AM/PM is specified, default to AM
if (!text.EndsWith("AM", StringComparison.OrdinalIgnoreCase) && !text.EndsWith("PM", StringComparison.OrdinalIgnoreCase))
{
text += " AM";
}
if (DateTime.TryParse(text, out DateTime time))
{
this.AssociatedObject.Text = time.ToString("h:mm tt", CultureInfo.InvariantCulture);
}
else
{
this.AssociatedObject.Text = "";
}
}
}
}