Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the simplest way to display NULL values as "NULL" with WPF Data Binding?

I have this legacy database for which I'm building a custom viewer using Linq to Sql.

Now some of the fields in a table can have the value NULL. Using normal databinding in a DataTemplate (typed for the Class generated by the ORM Designer)

<TextBlock Text="{Binding Path=columnX}"/>    

If columnX has value NULL, nothing is displayed. (It seems the to be the WPF convention) I'd like to display "NULL" instead if the value is NULL. (equivalent to column_value ?? "NULL")

I could use a converter as in

<TextBlock Text="{Binding Path=columnX, Converter={StaticResource nullValueConverter}}"/>

Converter class

class NullValueConverter : IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
    if (value == null)
      return "NULL";
    ...

But this seems like too much work. Also this logic would need to be duplicated in existing non-trivial converters..

Is there a quick-hit way to accomplish this?

like image 318
Gishu Avatar asked Jan 06 '09 10:01

Gishu


1 Answers

The binding class has a property called TargetNullValue that can be used to substitute something else if the binding returns a NULL value. Your example becomes:-

<TextBlock Text="{Binding Path=columnX, TargetNullValue=My Substitute Text}"/>

There is another property of the Binding class that is also useful called FallbackValue. This would be the substitute value to use if the binding expression cannot be resolved (i.e. not found), e.g for when the path you use (columnX in your example) is not a member of the data context or source.

Update(Gishu): Requires .NET Framework 3.5 SP1 a 53MB download. Without it, the above code won't compile. TargetNullValue is a new addition to the Binding class.

like image 116
Rhys Avatar answered Oct 15 '22 18:10

Rhys