FallbackValue and TargetNullValue in WPF Binding

WPF provides some magical features to deal with Null values in the bindings or dealing with the cases when binding fails. In this post, I will explain to you about these magical bindings which are FallbackValue and TargetNullValue.

There are many occurrences in our WPF bindings that we are not getting proper values from the source or it is Null or if the binding path is not correct etc. To handle these situations, WPF provides Fallback Values.

There are 2 types of Fallback Values in WPF.

1. TargetNullValue

As its name suggests, when the source object’s property is Null, then the target value is set by TargetNullValue. It’s an alternative value which you want to set the target when source value is null. or in simple words, we can say that it allows a value to be used if the bound property is null.

It is defined in the System.Windows.Data namespace.

public object TargetNullValue { get; set; }

Examples 1:

TargetNullValue Example 1

Examples 2:
There are many occasions in the code when we use checkboxes or radio buttons and we don’t want to set it either true or false. We want to have the checkbox in unchecked state. So to have checkbox unchecked by default, this TargetNullValue will do the magic for us. See the below example of the checkbox.

TargetNullValue Example 2

Now we have achieved what we wanted to do and it will look like a normal checkbox and the magic part is that this will not change our property. 🙂

2. FallbackValue

It is used to gets or sets the value when binding fails and the binding is unable to return a value. By default, DependencyProperty.UnsetValue is used.

FallbackValue is very useful when there is any problem in the binding or not able to resolve the binding source successfully. For example, the path of the bound property is incorrect, the property is not available, value converter is not able to convert a value into proper resulting value, resulting value is not valid for the target, etc. In this case, the binding will be failed and then FallbackValue will come into the picture and will set the value which is defined in this.

Syntax:

public object FallbackValue {get; set;}

Examples 1:

FallbackValue Example 1

Examples 2:
This is the best real-world example of FallbackValue. We use images in our projects and define the source of every image but there can be any reason that our binding fails and then we want to display our Default Image then FallbackValue is here to achieve it.

FallbackValue Example 2

Enjoy learning and leave your comment and suggestions regarding FallbackValue and TargetNullValue in WPF Binding.

Written by 

2 thoughts on “FallbackValue and TargetNullValue in WPF Binding

Leave a Reply

Your email address will not be published. Required fields are marked *