One of the ability of binding in WPF is the ability to support Fallback values. Fallback values are used when a binding comes up with an un-appropriate value which in turn can't be set on binding target. There are 2 types of Fallback values:
As its name communicate itself that when a source object’s property is null, then what is the alternate value you want to set for the target. So, whatever value is set for TargetNullValue, it will be set for target. Pretty simple, isn't it ?
This is used when a binding cannot come up with a value at all, based on the the data source and the path. Or in other words, FallbackValue is used when the property binded with source is not at all available. In that case, value supplied to FallbackValue will be considered at the target end.
Getting into the code:
Now, let’s jump on to the code on how to use both of these. Here aim is to bind the given text box with EmployeeName property.
My code behind class contain just the basic code to create a property for employee name, so that we can bind it with TextBox. Here goes the code:
Till this point, we haven’t done anything extra. It’s pretty simple and self-explanatory code. Let’s go ahead and quickly change the code a bit.
Demonstration of TargetNullValue:
As I mentioned earlier, TargetNullValue comes into picture only when your source object is null. To make source object null, let’s go ahead and do the minor changes into the code, as:
Now, next step is to set the value for TextBox, which will be displayed if source object (in our case source object is EmployeeName) is null. Let’s modify XAML file for this:
Now, when you will run the application, you will find the TargetNullValue is set for the TextBox as:
Demonstration of FallbackValue:
This FallbackValue will play its role when binding is not able to resolve the source. So, for this missing source, one can set the default value for the target. Let’s have a look at the code:
In above code, instead of binding TextBox to EmployeeName, I am binding it to EmployeeNames which is not the correct property as no such property is defined with this name. Hence my FallbackValue will come into picture and will give us the below output:
Hope this article was useful :)