在我的XAML中,我有以下的GridViewColumn
<GridViewColumn Header="Date Added" DisplayMemberBinding="{Binding DateAdded}" Width="80"/>绑定正常工作:在我的SQL表中有一个名为DateAdded的列,它对每个记录都有一个Unix时间戳值。当窗口加载时,它会显示一个包含所有列的ListView,但是添加日期的列具有实际时间戳(1516596663等)。
如何将时间戳值(即1516596663)转换为类似于January 22, 2018 4:51:03 AM的值
我在加载时设置ListView的方式如下--
crHistoryList.ItemsSource = _db.recordHistories.ToList();
dataListView = crHistoryList;(crHistoryList是我ListView的名字)
请注意:我不是在问如何将时间戳转换为人类可读的日期/时间.而是:在哪里输入转换逻辑,然后如何绑定转换逻辑,从而显示转换后的值,而不是从数据库检索的值。
发布于 2018-01-22 07:30:44
发布于 2018-01-22 09:09:59
如果有人在同一条船上,并希望(通过代码)看看如何做到这一点,请遵循构建converter的@Marc & @grek40 40的建议。
在.xaml文件中
在<Window x:Class=...之后添加以下内容
<Window.Resources>
<local:UnixTimestampConverter x:Key="utsConverter" />
</Window.Resources>其中UnixTimestampConverter是类文件的名称.utsConverter仅仅是类文件的名称,类文件在DisplayMemberBinding中引用如下所示--
<GridViewColumn Header="Date Added" DisplayMemberBinding="{Binding DateAdded, Converter={StaticResource utsConverter}}" Width="80"/>接下来,创建UnixTimestampConverter.cs文件
IValueConverter接口,因此将以下using指令添加到该类文件中:
using System.Windows.Data;Convert方法中进行转换.UnixTimestampConverter.cs的完整代码如下所示-
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
namespace myProject
{
class UnixTimestampConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null)
{
System.DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
dateTime = dateTime.AddSeconds(System.Convert.ToDouble(value)).ToLocalTime();
return dateTime;
}
else
{
return String.Empty;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
}
}
良好的转换器相关资源--
发布于 2018-01-22 09:16:59
正如Marc说的,您必须执行以下步骤:首先,将转换器类添加到项目中:
public class TimeStampToDate : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
try
{
double unixTimeStamp = System.Convert.ToDouble(value);
System.DateTime result = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
result = result.AddSeconds(unixTimeStamp).ToLocalTime();
return result;
}
catch (Exception)
{
return null;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}在第二步中,在xaml文件中添加转换器类的命名空间,如下所示:
xmlns:Converters="clr-namespace:Plugin.Converters" 第三步,在xaml文件中添加转换器作为资源:
<UserControl.Resources>
<ResourceDictionary>
<Converters:TimeStampToDate x:Key="TimeStampToDate"/>
</ResourceDictionary>
</UserControl.Resources>最后,您需要更改代码的某些部分:
<GridViewColumn Header="Date Added" DisplayMemberBinding="{Binding Path=DateAdded,Converter={StaticResource TimeStampToDate}}" Width="80"/>我希望这能帮到你。
https://stackoverflow.com/questions/48376413
复制相似问题