2013-11-28 194 views
3

我收集了一系列綁定到DataGrid的項目。不容易訪問集合本身,因此必須手動完成。在Xaml中將UTC日期時間轉換爲本地時區?

我在DataGrid上顯示的成員之一是DateTimeDateTime雖然是UTC,但需要在用戶當地時間顯示。

在XAML中是否有一個構造將讓一個將綁定的DateTime對象從UTC轉換爲本地時間?

+0

後的XAML和代碼。顯示格式應該在DataBinding屬性中指定。這假定您的DateTime值具有DateTimeKind屬性集。否則,您和.NET都不知道該值是否爲DateTimeKind.Utc或DateTimeKind.Local –

回答

1

您需要轉換器來轉換DateTime值。然後,字符串格式化仍然可像往常一樣:

class UtcToLocalDateTimeConverter : IValueConverter 
    { 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { 
     if (value is DateTime) 
      return ((DateTime)value).ToLocalTime(); 
     else 
      return DateTime.Parse(value?.ToString()).ToLocalTime(); 
    } 

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

啓發/用/從this SO question更新的答案,你會發現使用細節服用。

+0

爲什麼只將DateTime值轉換爲String纔將其解析回DateTime? –

+0

@PanagiotisKanavos你是對的,謝謝。現在修復,以避免輸入已經是DateTime類型的ToString/Parsing。 – Askolein

0

我會去與這一個:

public class UtcToZonedDateTimeConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     if (value == null) 
     { 
      return DateTime.MinValue; 
     } 

     if (value is DateTime) 
     { 
      return ((DateTime)value).ToLocalTime(); 
     } 

     DateTime parsedResult; 
     if (DateTime.TryParse(value?.ToString(), out parsedResult)) 
     { 
      return parsedResult.ToLocalTime(); 
     } 

     return DateTime.MinValue; 
    } 

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