Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?
like image 805
sdgfsdh Avatar asked Oct 29 '15 14:10

sdgfsdh


People also ask

What is FallbackValue?

This is used when a binding cannot determine a value at all, based on the the data source and the path. Or in other words, FallbackValue is used when the property bound to the source is not at all available. In that case, the value supplied for FallbackValue will be considered at the target end.

What is the default binding mode in WPF?

Default Data-binding It just defines which is the default binding mode for the control's property. In WPF different controls has different default data-binding modes. For example, TextBlock's Text property has one-way as default binding mode but a TextBox's Text property has a two-way binding mode.

How many types of binding are there in WPF?

WPF binding offers four types of Binding. Remember, Binding runs on UI thread unless otherwise you specify it to run otherwise. OneWay: The target property will listen to the source property being changed and will update itself.

What is element binding in WPF?

Data binding in Windows Presentation Foundation (WPF) provides a simple and consistent way for apps to present and interact with data. Elements can be bound to data from different kinds of data sources in the form of . NET objects and XML.


1 Answers

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>
like image 175
Nathan Kovner Avatar answered Dec 15 '22 14:12

Nathan Kovner