在我的XAML中,我有以下GridViewColumn
<GridViewColumn Header="Date Added" DisplayMemberBinding="{Binding DateAdded}" Width="80"/>
绑定按预期工作:我的SQL表中有一个名为DateAdded
的列,每个记录都有一个Unix Timestamp值。加载窗口时,它会显示包含所有列的ListView
,但添加日期列具有实际时间戳(1516596663
等)。
如何将时间戳值(即1516596663
)转换为January 22, 2018 4:51:03 AM
之类的内容?
我在加载时设置ListView
的方式如下 -
crHistoryList.ItemsSource = _db.recordHistories.ToList();
dataListView = crHistoryList;
(crHistoryList
是我的ListView
)
请注意: 我不是要求如何从UNIX时间戳转换为人类可读的日期/时间...而是:在哪里输入转换逻辑然后如何绑定它,因此它显示转换后的值而不是从数据库中检索的值。
答案 0 :(得分:0)
我可以为您提供两步解决方案:
答案 1 :(得分:0)
如果有人在同一条船上,并希望(通过代码)看到如何执行此操作,请遵循@Marc&amp; @ grek40构建converter
.xaml
文件在<Window x:Class=...
<Window.Resources>
<local:UnixTimestampConverter x:Key="utsConverter" />
</Window.Resources>
其中UnixTimestampConverter
是您的类文件的名称.... utsConverter
只是类文件的名称,应在DisplayMemberBinding
中引用,如下所示 - < / p>
<GridViewColumn Header="Date Added" DisplayMemberBinding="{Binding DateAdded, Converter={StaticResource utsConverter}}" Width="80"/>
UnixTimestampConverter.cs
文件因为此文件将实现IValueConverter
接口,所以将以下using
指令添加到此类文件中:
using System.Windows.Data;
接下来,实施界面,在Convert
方法中,将发生转换 ... UnixTimestampConverter.cs
的完整代码如下所示 - < / p>
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;
}
}
}
&#13;
良好的转换器相关资源 -
Value conversion with IValueConverter ---感谢@Marc
答案 2 :(得分:0)
正如Marc所说,你必须采取以下措施: 首先将Converter Class添加到您的项目中:
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"/>
我希望这可以帮到你。