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

时间:2016-07-25 19:22:30

标签: c# wpf xaml

我在wpf应用程序中有textblock,我绑定了一个显示日期和时间的字符串属性。有没有办法在字符串属性上应用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>

输出仍然是7/25/2016 12:20:23 PM

2 个答案:

答案 0 :(得分:0)

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

我建议有第二个属性:

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

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

此外,您可以创建一个实现IValueConverter的类来执行相同的操作。您可以使用StringToDateTime转换器,如果您希望它具有更强的适应性,仍然可以使用StringFormat属性,或者您可以执行TimestampConverter并将string更改为DateTime,使用上面的格式字符串格式化DateTime,并输出string本身。在此迭代中,您不需要StringFormat属性。

答案 1 :(得分:0)

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