您需要添加一个 IValueConverter 以将您的 string 对象更改为 DateTime。像这样的。
public class StringToDateValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return DateTime.Parse(value.ToString());
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
当然,您会想要实现某种形式的验证逻辑,为了简单起见,我已将其排除在外。
标记...
<Window x:Class="WpfApplication4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication4"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:ViewModel />
</Window.DataContext>
<Window.Resources>
<local:StringToDateValueConverter x:Key="converter" />
</Window.Resources>
<Grid>
<TextBlock Grid.Row="0" Grid.Column="2" HorizontalAlignment="Right" Margin="25,5,0,0" Text="{Binding alertTimeStamp, Converter={StaticResource converter}, StringFormat=dd MMM yyyy hh:mm:ss tt}"></TextBlock>
</Grid>
</Window>