6

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?

Gishu
  • 134,492
  • 47
  • 225
  • 308

3 Answers3

18

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.

Gishu
  • 134,492
  • 47
  • 225
  • 308
Rhys
  • 4,511
  • 2
  • 23
  • 32
0

Right click on the DBML file, click View code. Add a partial class for the table you want to work with. Add a property returning value ?? null or something like that. The trick is that LINQ to SQL declares the classes as partial, so you can easily extend them.

Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
0

I don't think there's a cleaner way to do it. You could possibly use a DataTrigger in a style template to pick up on null values, but data triggers can be a bit "funny" when using NULLs so you'd likely need a converter anyway.

Steven Robbins
  • 26,441
  • 7
  • 76
  • 90