datetime converter WPF

牧云@^-^@ 提交于 2019-12-11 04:53:26

问题


I have this converter that i made to get the current time once the date is selected from the DataPicker. In string Date i am getting the value that was selected from the DatePicker, but i cant seem to only get the date. The format that is coming into the Value property is 9/24/2013 12:00:00 I would like it to be 9/24/2013

the error i am getting is "Error 122 No overload for method 'ToString' takes 1 argument"

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
            if (value is DateTime)
            {
            string date = value.ToString("d/M/yyyy");
            return (date);
            }

             return string.Empty;
}

回答1:


You need to cast it to DateTime first:

public object Convert(object value, Type targetType, object parameter,
                      System.Globalization.CultureInfo culture)
{
    if (value is DateTime)
    {
        DateTime test = (DateTime) value;
        string date = test.ToString("d/M/yyyy");
        return date;
    }

    return string.Empty;
}



回答2:


You should cast value to DateTime type, because there is not a ToString(String f) method for the type of Object.

if (value is DateTime)
{
   var dateTime = (DateTime)value;
   return dateTime.ToString("dd/MM/yyyy");
}

return string.Empty;



回答3:


After check on type of value you need cast it to appropriate type, to be able to perform "ToString" call with format parameter. Try:

if (value is DateTime)
{
    var dateValue = value as DateTime;
    string date = dateValue.ToString("dd/MM/yyyy");
    return date; 
}



回答4:


If you are using a Converter on a WPF DatePicker control, you should note that the WPF DatePicker will itself reformat the date despite the converter that you use. You will have to style the Datepicker to include a StringFormat.

There is a related question here: how to show just Month Year string format in a DatePicker which shows an attached property to modify the behaviour of DatePicker to display a custom format. This is needed because of a deficiency in the WPF Datepicker control itself.

Also note there are some caveats, notably the DatePicker will flicker between its default stringformat and the one you apply! I answered in the above question a workaround for to apply a custom Format to WPF Datepicker without the flicker.

Hope you find the solution you are looking for.




回答5:


public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    if (value is DateTime)
    {
        string date=value.Date.ToShortDateString();
        return (date);
    }

    return string.Empty;
}


来源:https://stackoverflow.com/questions/18638575/datetime-converter-wpf

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