Lets say i have a TextBlock thats bound to a DateTime, is there any way to replace the value 0001-01-01 00:00:00 with an empty string?
You have a few options:
DateTime?
(that is, Nullable<DateTime>
) rather than DateTime
. Set the value to null
when you want nothing to appear.DateTime.MinValue
to an empty string
.DateTime.MinValue
to an empty string
.Example of #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");
}
}
}
}
Example of #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; }
}
}
Example of #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;
}
...
}