Consider the following piece of XAML (part of an Image Viewer application), that wants to set the Window title (in WPF) based on the currently loaded image file:
This assumes that a DataContext exists, and exposes a property named ImagePath. This works well if such an object actually exists. But what happens when the application starts up and there is no image loaded yet, meaning the DataContext remains null? The Title would show nothing, because the binding fails. How can we fix that?
One way would be to create a dummy DataContext with the ImagePath property set to some value we want. But that’s cumbersome and limiting. What if we wanted a completely different title when there is no image?
Fortunately, there is a way. The FallbackValue property of the Binding object (actually BindingBase) allows setting a value if the binding can’t complete. Here’s a way to get something with a null DataContext:
This shows the fallback value when the binding is unable to provide a value.