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

后端 未结 1 454
北荒
北荒 2021-01-28 08:10

Simplified Question:

I have a datepicker in WPF. I enter a value 30/10/1983 in the textbox of the datepicker. I need the value to be posted back to my v

相关标签:
1条回答
  • 2021-01-28 08:39

    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}}"
      />
    
    0 讨论(0)
提交回复
热议问题