Reputation: 2500
I have a column that is bound to a property of my object. The property, LastRunDate, is a Datetime. On default/start, it displays a date along the lines of of 1/1/1 12:00 AM.
Is there a way in my XAML to format my date where if I have a date of this value, to instead show a string of "None" or even a blank? Is there a way I can put this into my string format?
Here's the XAML right now:
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name}" Header="Name" />
<DataGridTextColumn Binding="{Binding SourceServerName}" Header="Server Source" />
<DataGridTextColumn Binding="{Binding SourceDataBaseName}" Header="Database" />
<DataGridTextColumn Binding="{Binding LastRunTime, StringFormat={}\{0:MM/dd/yyyy hh:mm\}}" Header="Last Run Time" />
</DataGrid.Columns>
Upvotes: 1
Views: 3185
Reputation: 10744
Converter:
class DateTimeConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is DateTime)
{
var test = (DateTime)value;
if (test == DateTime.MinValue)
{
return "None";
}
var date = test.ToString("MM/dd/yyyy hh:mm");
return (date);
}
return string.Empty;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
XAML:
<DataGrid ItemsSource="{Binding Items}">
<DataGrid.Resources>
<stackOverflow:DateTimeConverter x:Key="DateTimeConverter"/>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding LastRunTime, Converter={StaticResource DateTimeConverter}}" Header="Last Run Time" />
</DataGrid.Columns>
</DataGrid>
Upvotes: 3
Reputation: 33381
Change the type of LastRunDate
to Datetime?
. Then use this:
<DataGridTextColumn Binding="{Binding LastRunTime, TargetNullValue=None,
StringFormat={}\{0:MM/dd/yyyy hh:mm\}}" Header="Last Run Time" />
Since your property isn't initialized on start (i.e. it is null
), you will see "None".
Upvotes: 1