【问题标题】:Binding string property to textblock and apply custom date format将字符串属性绑定到文本块并应用自定义日期格式
【发布时间】:2016-07-25 19:22:30
【问题描述】:

我在一个 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>

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

【问题讨论】:

标签: c# wpf xaml


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    我建议拥有第二个属性:

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

    然后将AlertTimeStampDateTime 属性绑定到具有相同StringFormat 属性的&lt;TextBlock /&gt; 对象。

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

    【讨论】:

    • 当然让我试一试。
    猜你喜欢
    • 1970-01-01
    • 2019-02-16
    • 2021-03-21
    • 1970-01-01
    • 2020-07-06
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    相关资源
    最近更新 更多