DateTimePicker + WPF + binding + accept dd/MM/yyyy via userinput

ⅰ亾dé卋堺 提交于 2019-12-02 10:27:43

The problem is related that a not valid date will not set with a correct value your ViewModel DateTime property. So, you can intercept it and convert correctly with a CONVERTER.

An example:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string strValue = System.Convert.ToString(value);
        DateTime resultDateTime;
        if (DateTime.TryParse(strValue, out resultDateTime))
        {
            return resultDateTime;
        }
        return value;    
    }

And your XAML code will be like:

 <DatePicker 
     Text="{Binding BirthDate,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
     SelectedDate="{Binding RelativeSource={RelativeSource Self},Path=Text,
     Converter={StaticResource DateConverter}}"
  />
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!