views:

471

answers:

2

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 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.

+1  A: 

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}"/>
Aviad P.
This seems to be a good solution in theory, however for the datepicker, the wpf beats me to the conversion and an exception is thrown on LostFocus '"String was not recognized as a valid DateTime."'. How can I do the conversion "before" the wpf framework tries to do it for me? I'm tempted to use the lostFocus event solution.. winforms-style :(
Tewr
Wait, are you using a `TextBox` or a `DatePicker` from the WPF toolkit?
Aviad P.
wpf toolkit DatePicker
Tewr
Oh man, I'm sorry I misunderstood your question :)
Aviad P.
A: 

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;
                        }
                }
            }

        }
    }
Tewr