WPf Datepicker Input modification
I am creating a form using wpf/c#. I am looking to programatically change/interpret the user's typed input in the wpf toolkit DatePicker
.
For example, the user types "Today", and when the control looses focus the date is interpreted and set to the current date using my c# function.
Should I listen to the lostFocus event or is there a better开发者_Go百科 way of changing how a typed input date is parsed?
I do not care to change the display format of the date picker. I am developing this application using the mvvm pattern.
Ok so finally I looked into the sourcecode of DatePicker
and theres not much I can do in terms of converters etc as most stuff is private and the only two available formats are "short" and "long". Finally, I will have to create my own control, probably in part using the solution above by Aviad. However, here's a quick temporary solution until then (where DateHelper
is my custom parser class):
public class CustomDatePicker : DatePicker
{
protected override void OnPreviewKeyDown(KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
this.TryTransformDate();
}
base.OnPreviewKeyDown(e);
}
protected override void OnPreviewLostKeyboardFocus(KeyboardFocusChangedEventArgs e)
{
this.TryTransformDate();
base.OnPreviewLostKeyboardFocus(e);
}
protected void TryTransformDate()
{
DateTime tryDate;
if (DateHelper.TryParseDate(this.Text, out tryDate))
{
switch (this.SelectedDateFormat)
{
case DatePickerFormat.Short:
{
this.Text = tryDate.ToShortDateString();
break;
}
case DatePickerFormat.Long:
{
this.Text = tryDate.ToLongDateString();
break;
}
}
}
}
}
Typical scenario for a value converter. Define a value converter that accepts a string
and converts it to a DateTime
. In your binding, define the UpdateSourceTrigger
to be LostFocus
thus:
<TextBox Text="{Binding DateText,
Converter={StaticResource MyConverter},
UpdateSourceTrigger=LostFocus}"/>
精彩评论