问题描述:

What I have:

1. a textblock in the XAML

2. a query from a database which contains a DateTime? type data.


What I do:

1. I declare a class "myClass" with a DateTime? parameter named "myDate"


What I want

1. show the MyDate in the textblock [I know]

2. when the value of "myDate" is null, show a string in the textblock. [I don't know, because the Get method can only return a DateTime? type value but not a String type.]

网友答案:

Try using Binding with your textblock like this :

<TextBlock Text="{Binding myDate, TargetNullValue='Your null message'"/>
网友答案:

You should write a converter which will do 'is null' check and return information string when it is.

This will allow you do it directly from XAML, using standard Data Binding, without any additional code in code-behind file.

网友答案:

Declare a string variable; if myDate is not null, assign it the date's value - otherwise set it to whatever the default is. Examples:

string stringToShow = null;
if(myDate.HasValue)
{
  stringToShow = myDate.Value.ToString();
}
else
{
  stringToShow = "other string";
}

or, more concisely with a ternary

string stringToShow = myDate.HasValue ? myDate.Value.ToString() : "other string";

Then show stringToShow in the textblock instead of myDate. Finally, you could wrap this in an extension method to make it super easy to call:

public static string ToSpecialString(this DateTime? date)
{
  return myDate.HasValue ? myDate.Value.ToString() : "other string";
}

Then you can just call myDate.ToSpecialString() in the front end.

相关阅读:
Top