假设我有一个绑定到DateTime的TextBlock,有没有办法用空字符串替换值0001-01-01 00:00:00?
答案 0 :(得分:3)
您有几个选择:
DateTime?
(即Nullable<DateTime>
)而不是DateTime
。如果您不想显示任何内容,请将值设置为null
。DateTime.MinValue
转换为空string
。DateTime.MinValue
转换为空string
。#1的示例
<TextBlock Text="{Binding SomeDateTime}"/>
public class YourViewModel : ViewModel
{
private DateTime? _someDateTime;
public DateTime? SomeDateTime
{
get { return _someDateTime; }
set
{
if (_someDateTime != value)
{
_someDateTime = value;
OnPropertyChanged("SomeDateTime");
}
}
}
}
#2的例子
<TextBlock Text="{Binding SomeDateTimeString}"/>
public class YourViewModel : ViewModel
{
private DateTime _someDateTime;
public DateTime SomeDateTime
{
get { return _someDateTime; }
set
{
if (_someDateTime != value)
{
_someDateTime = value;
OnPropertyChanged("SomeDateTime");
OnPropertyChanged("SomeDateTimeString");
}
}
}
public string SomeDateTimeString
{
get { return SomeDateTime == DateTime.MinValue ? "" : SomeDateTime; }
}
}
#3的例子
<!-- in resources -->
<local:DateTimeConverter x:Key="YourConverter"/>
<TextBlock Text="{Binding SomeDateTime, Converter={StaticResource YourConverter}}"/>
public class YourClass
{
private DateTime _someDateTime;
public DateTime SomeDateTime
{
get { return _someDateTime; }
set
{
if (_someDateTime != value)
{
_someDateTime = value;
OnPropertyChanged("SomeDateTime");
}
}
}
}
public class DateTimeConverter : IValueConverter
{
public object Convert(object value ...)
{
return value == DateTime.MinValue ? "" : value;
}
...
}
答案 1 :(得分:1)
使用转换器格式化日期
转换代码:
public class MyDateConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
DateTime dt = (DateTime)value;
if (dt == dt.MinValue)
return "";
else
return dt.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
string s = (string)value;
if (string.IsNullOrEmpty(s))
return DateTime.MinValue;
else
return DateTime.Parse(s);
}
}
XAML:
...
<Window.Resources>
<local:MyDateConverter x:Key="dateConverter"/>
</Window.Resources/>
...
<TextBlock Text="{Binding TheDate, Converter={StaticResource dateConverter}}"/>