Custom date format for textbox

后端 未结 1 409
礼貌的吻别
礼貌的吻别 2021-01-23 00:33

Related: Binding 3 textboxes together; same DateTime different format

I have three textboxes, all are supposed to be bound together with the same date. Two

1条回答
  •  抹茶落季
    2021-01-23 00:55

    You need to set the convert back in the converter. This is just an example but you need to parse the value back into original source so other binds can be updated.

    since your format is {0},{1}/{2} then you need to split it back up and reconstruct the intended date.

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null) return null;
        string strValue = value.ToString();
        if (string.IsNullOrEmpty(strValue) && targetType == typeof(DateTime?))
        {
            return null;
        }
        else if (string.IsNullOrEmpty(strValue))
        {
            return DateTime.MinValue;
        }
    
        //year,dayOfYear/Time(HHmmss)
        var parts = strValue.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
        if (parts.Length == 2) {
            var year = parts[0];
            parts = parts[1].Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            if (parts.Length == 2) {
                var days = parts[0];
                var time = parts[1];
    
                var date = new DateTime(int.Parse(year), 1, 1)
                                .AddDays(int.Parse(days))
                                .Add(TimeSpan.Parse(time));
                return date;
            }
        }
    
        DateTime resultDateTime;
        return DateTime.TryParse(strValue, out resultDateTime) ? resultDateTime : value;
    }
    

    0 讨论(0)
提交回复
热议问题