Custom date format for textbox

主宰稳场 提交于 2020-01-02 10:33:12

问题


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 of them have normal string formats. The third one has a specific format of yyyy,jjj/HHmmss. I can't figure out how to bind this textbox to the custom format I have, and make it so if I change any of the date values in it, the other textboxes will update and vice versa.

private DateTime _dateInViewModel;
public DateTime DateInViewModel
{
    get { return _dateInViewModel; }
    set
    {
        _dateInViewModel = value;
        NotifyPropertyChanged("DateInViewModel");
    }
}

<TextBox Name="SDate1" Text="{Binding DateInViewModel, StringFormat='MM/dd/yyyy'}" />
<TextBox Name="SDate2" Text="{Binding DateInViewModel}" />
<TextBox Name="STime1" Text="{Binding DateInViewModel, StringFormat='hh:mm:ss'}" />

The custom format can be made like:

format = String.Format("{0},{1}/{2}",
                                DateInViewModel.Year,
                                DateInViewModel.DayOfYear.ToString("d3"),
                                DateInViewModel.ToString("HHmmss"));

Right now, only SDate1 and STime1 bind to each other properly and update when the other is changed.

I made a converter. It properly updates SDate2 when SDate1 and STime1 are changed, but doesn't work when editing SDate2 to update the others.

public class DateTimeConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value != null)
        {
            DateTime test = (DateTime)value;
            string date = String.Format("{0},{1}/{2}",
                                            test.Year,
                                            test.DayOfYear.ToString("d3"),
                                            test.ToString("HHmmss"));
            return (date);
        }
        return string.Empty;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}


回答1:


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


来源:https://stackoverflow.com/questions/36088998/custom-date-format-for-textbox

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