Insert DateTime format in combobox

无人久伴 提交于 2019-12-13 05:46:20

问题


I've Harvest_Base class where all DateTime formats are shown;

class Harvest_Base
{

    public static DateTime storeTime(String date)
    {

        DateTime returnValue = new DateTime();

        if (date == "")
            return returnValue;

            //Time or Date Component Does not Exist
            string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", 
               "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", 
               "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", "M/d/yyyy h:mm", "M/d/yyyy h:mm", 
               "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm", 
               "h:mm tt","hh:mm tt","HH:mm:ss","H:mm","HH:mm","h:mmtt"};
            DateTime result;

            if (DateTime.TryParseExact(date, formats, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
                returnValue = result;
            else
                returnValue = DateTime.Today;

        return returnValue;

    }

}

I have view class in which I've two comboboxes for starttime and stoptime. I want to do something bu which these comboBoxes should show me values in "hh:mm tt" format.

My questions are:

  1. Is binding required here? If yes, please explain with code in answer.

  2. If binding not required then what can I do to achieve this result?


回答1:


Either you bind the combo box directly to the DateTime and apply a StringFormat on the binding, or you bind to a string representing your DateTime in the proper format. You could also use a value converter, but it's a bit overkill.

Here's the StringFormat in the Binding clause

{Binding Path=PathToTheDateTime, StringFormat={}{0:MM-dd-yyyy}}

Change the MM-dd-yyyy part to your liking.



来源:https://stackoverflow.com/questions/17593906/insert-datetime-format-in-combobox

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