WPF/Silverlight Data Binding Tip: FallbackValue

June 25, 2011

no comments

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:

Title="{Binding ImagePath, StringFormat=Image Viewer ({0})}"

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:

Title="{Binding ImagePath, StringFormat=Image Viewer ({0}), FallbackValue=Image Viewer Select Open to load a file}"

This shows the fallback value when the binding is unable to provide a value.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>