views:

923

answers:

4

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?

A: 

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
This might take a while.. doing this for nullable fields for every table.
Gishu
A: 

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
+11  A: 

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.

Rhys
Seems to be a .Net 3.5 Framework SP1 addition... sadly I dont have it.
Gishu
I installed SP1... the solution works. This seems more like 'how it should be'. Thanks Rhys!
Gishu
Learn somethign new every day.. didn't see them sneak that one in for SP1.. cheers :)
Steven Robbins
A: 

what's the TargetNullValue for ? It's the default dataContext ? Or it the default property value ?

xiemails
default property value.
Gishu