我需要格式化日期,所以我使用了以下内容:
<xcdg:Column Title="Registratiedatum" FieldName="RegistratieDatum" Width="1*">
<xcdg:Column.CellContentTemplate>
<DataTemplate>
<TextBlock Text="{Binding StringFormat='{}{0:dd/MM/yyyy HH:mm:ss }', TargetNullValue={x:Static System:String.Empty}}" />
</DataTemplate>
</xcdg:Column.CellContentTemplate>
</xcdg:Column>
但是,有些日期为 Null,所以我希望这些字段保持为空,但我想由于格式原因,它看起来像这样:
01/01/0001 00:00:00
知道如何限制“非空”值的格式吗?对不起,如果这可能是太基础的问题,但我仍处于学习的初级阶段。
最佳答案
A Struct
作为value type
, 它永远不可能是 null
.
但是,有几种方法可以解决您的问题:
在我看来,最简洁、最合乎逻辑的方法是将 DateTime 更改为
Nullable<Datetime>
private DateTime? myDate; public DateTime? MyDate { get { return this.myDate; } set { this.myDate = value; } }
如果这不是一个选项,转换器可以解决问题:
.xaml代码:
<UserControl.Resources> <local:DateConverter x:Key="dateConverter"/> </UserControl.Resources> <TextBlock Text="{Binding MyDate, Converter={StaticResource dateConverter}}" />
.cs代码
public class DateConverter: IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value != null) { DateTime myDate = (DateTime)value; if (myDate != DateTime.MinValue) { return myDate.ToString("dd/MM/yyyy HH:mm:ss"); } } return String.Empty; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }
最后,直接在 Xaml 代码中的 DataTrigger 允许您在日期为 null 时隐藏/折叠控件。在转换器中,关键是检查日期何时等于
DateTime.MinValue
.<UserControl x:Class="WpfApplicationTest.MyUserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:local="clr-namespace:WpfApplicationTest" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"> <TextBlock Text="{Binding MyDate, StringFormat='{}{0:dd/MM/yyyy HH:mm:ss }'}" > <TextBlock.Style> <Style TargetType="TextBlock"> <Style.Triggers> <DataTrigger Binding="{Binding MyDate}" Value="{x:Static sys:DateTime.MinValue}"> <Setter Property="Visibility" Value="Collapsed"></Setter> </DataTrigger> </Style.Triggers> </Style> </TextBlock.Style> </TextBlock>
关于WPF 日期时间格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38186404/