2010-09-07 303 views
1

我有一個名爲Raised_Time的屬性,這個屬性顯示了在datagrid Cell中引發警報的時間。當用戶創建任何警報時,我不想在datagrid單元格中顯示任何內容,只顯示空單元格。如何將DateTime的默認值設置爲空字符串?

我在互聯網上搜索並發現DateTime的默認值可以使用DateTime.MinValue進行設置,並且這將顯示日期時間i的最小值:e「1/1/0001 12:00:00 AM」。

相反,我希望datagrid單元保持空白,直到發出警報時,它不顯示任何時間。

我認爲datatrigger可以寫在這種情況下。我無法爲此場景編寫數據觸發器。我是否還需要一個轉換器來檢查DateTime是否設置爲DateTime.MinValue,使datagrid單元格保持空白?

請幫忙!!

+2

在互聯網上用谷歌搜索..不錯;) – Arcturus 2010-09-07 12:37:30

回答

3

如何只改變你的財產鏈接到的DateTime的私人領域如:

public string Raised_Time 
{ 
    get 
    { 
    if(fieldRaisedTime == DateTime.MinValue) 
    { 
     return string.Empty(); 
    } 
    return DateTime.ToString(); 
    } 
    set 
    { 
    fieldRaisedTime = DateTime.Parse(value, System.Globalization.CultureInfo.InvariantCulture); 
    } 
} 
+0

什麼是價值來自一個實體框架創建的對象...從DB .... – Dani 2013-03-22 14:23:03

1

我用這個nullable datetime,具有擴展方法,如:

public static string ToStringOrEmpty(this DateTime? dt, string format) 
{ 
    if (dt == null) 
     return string.Empty; 

    return dt.Value.ToString(format); 
} 
+0

好點兄弟!謝謝,++++! ) – 2012-11-12 22:52:33

7

我看到兩個簡單的選項來解決這個問題:

  1. 您使用Nullable數據類型DateTime?,這樣如果鬧鐘時間未設置,您可以存儲null而不是DateTime.MinValue

  2. 您可以使用轉換器,here is an example

7

我會使用一個轉換器,因爲這是我可以很容易地看到在未來重用。這是我曾經使用過的一個DateFormat的字符串值作爲ConverterParameter。

public class DateTimeFormatConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     if ((DateTime)value == DateTime.MinValue) 
      return string.Empty; 
     else 
      return ((DateTime)value).ToString((string)parameter); 
    } 


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