Search code examples
wpfxamlbindingnullreferenceexception

Null checking in binding expression


Does WPF binding expression syntax have a null-checking mechanism? So for example My TextBox shows the Address field of the first element of an array of People objects, like this:

Text="{Binding AllPeople[0].Address}" 

AllPeople can at times be null itself. This doesn't cause any exceptions, but WPF silently records an binding error message in the Immediate window. Is there a way to avoid this by specifying null-safety in the Path expression? Something on the lines of AllPeople?[0].Address.

Note: I know this can easily be done using Converters. I'm looking for a shorthand notation.


Solution

  • In your binding, you can configure two optional properties: TargetNullValue and FallbackValue. The first one should be what you need.

    The FallbackValue will be applied if the binding does not work at runtime.

    Example:

    IsEnabled="{Binding Path=EnabledFlagInViewModel, TargetNullValue=false}"