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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With