将字符串属性绑定到文本块并应用自定义日期格式

本文关键字:应用 自定义 日期 格式 文本 字符串 属性 绑定 | 更新日期: 2023-09-27 17:58:36

我在wpf应用程序中有一个文本块,我正在绑定一个显示日期和时间的字符串属性。有没有一种方法可以对字符串属性应用StringFormat来格式化日期内容。我试了以下方法,但没用。请帮忙。

在模型中,属性为

   public string alertTimeStamp { get; set; }

在视图中,我正在尝试

<TextBlock Grid.Row="0" Grid.Column="2" HorizontalAlignment="Right" Margin="25,5,0,0" Text="{Binding alertTimeStamp, StringFormat=0:dd MMM yyyy hh:mm:ss tt}"></TextBlock>

输出仍然是2016年7月25日下午12:20:23

将字符串属性绑定到文本块并应用自定义日期格式

您需要添加一个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>

我怀疑这里的问题是alertTimeStamp已经是一个字符串,因此不能通过StringFormat属性更改它。

我建议拥有第二处房产:

public DateTime AlertTimeStampDateTime
{
    get { return DateTime.Parse(this.alertTimeStamp); }
}

然后将AlertTimeStampDateTime属性绑定到具有相同StringFormat属性的<TextBlock />对象。

此外,您还可以创建一个实现IValueConverter的类,该类可以做同样的事情。你可以做一个StringToDateTime转换器,如果你想让它更具适应性,仍然使用StringFormat属性,或者你可以做TimestampConverter,让它把string改成DateTime,用上面的格式字符串格式化DateTime,然后输出string本身。在这个迭代中,您不需要StringFormat属性。