In WPF, is the FallbackValue used when the binding fails due to null references?

sdgfsdh picture sdgfsdh · Oct 29, 2015 · Viewed 10.6k times · Source

My view-model exposes a list called MyList that may be empty or null. I have an element that I would like hide based on this state. If MyList is empty or null, then the element should be collapsed. If it has elements then it should be shown.

Here is my DataTrigger:

<DataTrigger Binding="{Binding MyList.Count, FallbackValue=0}" Value="0">
    <Setter Property="Visibility" Value="Collapsed"></Setter>
</DataTrigger>
  • What happens to this DataTrigger when MyList is null?
  • Will it use the FallbackValue or will it fail?
  • Is this documented somewhere?

Answer

Nathan Kovner picture Nathan Kovner · Oct 29, 2015

The FallbackValue is used if the binding source path does not resolve, if the converter fails, or if the value is not valid for the property's type.

It will not be used if null is returned, unless null is not valid for the property type. In this case the DataTrigger will not be triggered. You can use TargetNullValue for this case.

<DataTrigger Binding="{Binding MyList.Count, FallbackValue=0, TargetNullValue=0}" Value="0">
    <Setter Property="Visibility" Value="Collapsed"></Setter>
</DataTrigger>