WPf Datepicker Input modification

喜你入骨 提交于 2019-12-24 00:28:38

问题


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:


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

        }
    }



回答2:


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}"/>


来源:https://stackoverflow.com/questions/2000534/wpf-datepicker-input-modification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!