Fallback And Target Null Values In WPF

Welcome back all.

Let’s continue our exploration of WPF.
 
Today we will unravel the purpose of Fallback and TargetNull values.
 

Introduction

 
In order to unravel this mystery, we can take help from our friend C#. If you have studied design patterns in C#, then you might be familiar with the Null Object Design pattern.
 
Let me brief you a bit.

We basically assign some default value to object type, so whenever a null value is expected we can simply replace it with the assigned default value.

That way we can always have something to show rather than showing null values to the user.

WPF has this behaviour integrated so we can deal with null values in a much simpler way.
 
Let's understand this through an example.
 
Say we have a college admission form which has basic fields, such as
  • Name: Textbox
  • Date of birth: DateTime
  • Age: Textbox
  • Gender: RadioButtons for male & female
  • Nationality: checkbox for specifying if nationality is Indian
  • Register button
  • Textblock for a message on successful admission. 
Here is a glance at the UI: Specifying datatype of each field.
 
 
Mainwindow.xaml
  1. <Window x:Class="LearnWPF.MainWindow"    
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    
  4.         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"    
  5.         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"    
  6.         xmlns:local="clr-namespace:LearnWPF.ViewModel"    
  7.          mc:Ignorable="d"    
  8.         Title="MainWindow" Height="200" Width="400">    
  9.     <Window.Resources>    
  10.         <local:MainWindowViewModel x:Key="VM" />    
  11.         <Style x:Key="SubmitButtonStyle"        
  12.            BasedOn="{StaticResource {x:Type Button}}"        
  13.            TargetType="Button">    
  14.             <Setter Property="Height" Value="25"/>    
  15.             <Setter Property="Width" Value="150"/>    
  16.             <Setter Property="BorderThickness" Value="2"/>    
  17.             <Setter Property="BorderThickness" Value="2"/>    
  18.             <Setter Property="HorizontalAlignment" Value="Center"/>    
  19.             <Setter Property="VerticalAlignment" Value="Center"/>    
  20.     
  21.             <Setter Property="Content" Value="Trigger Not Applied"/>    
  22.             <Setter Property="BorderBrush" Value="Black"/>    
  23.             <Setter Property="Background" Value="Gray"/>    
  24.             <Setter Property="Foreground" Value="Wheat"/>    
  25.             <Style.Triggers>    
  26.                 <MultiTrigger>    
  27.                     <MultiTrigger.Conditions>    
  28.                         <Condition Property="IsMouseOver" Value="True"/>    
  29.                         <Condition Property="IsKeyboardFocused" Value="True"/>    
  30.                     </MultiTrigger.Conditions>    
  31.                     <MultiTrigger.Setters>    
  32.                         <Setter Property="Content" Value="Trigger Applied"/>    
  33.                         <Setter Property="BorderBrush" Value="White"/>    
  34.                         <Setter Property="Background" Value="SkyBlue"/>    
  35.                         <Setter Property="Foreground" Value="Black"/>    
  36.                     </MultiTrigger.Setters>    
  37.                 </MultiTrigger>    
  38.             </Style.Triggers>    
  39.         </Style>    
  40.     
  41.     </Window.Resources>    
  42.     <Grid  DataContext="{Binding Source={StaticResource VM}}">    
  43.         <Grid.RowDefinitions>    
  44.             <RowDefinition/>    
  45.             <RowDefinition/>    
  46.         </Grid.RowDefinitions>    
  47.     
  48.         <StackPanel x:Name="MainGrid"    
  49.                 Orientation="Horizontal"    
  50.                 HorizontalAlignment="Center">    
  51.             <Button x:Name="ButtonStyleMe"       
  52.                  Style="{StaticResource SubmitButtonStyle}"    
  53.                     Command="{Binding StyledButtonCliked}"/>    
  54.             <Button x:Name="ButtonCancel"       
  55.                 Content="Cancel"    
  56.                 Height="25"    
  57.                 Margin="10 0 0 0"    
  58.                 Width="150"    
  59.                 Command="{Binding CancelButtonCliked}"/>    
  60.         </StackPanel>    
  61.         <TextBlock Text="{Binding FocusText}"    
  62.                    HorizontalAlignment="Center"    
  63.                    Grid.Row="1"/>    
  64.     </Grid>    
  65. </Window>    
MainWindowViewModel.cs
  1. using System;  
  2. using Prism.Commands;  
  3. using Prism.Mvvm;  
  4.   
  5. namespace LearnWPF.ViewModel  
  6. {  
  7.     public class MainWindowViewModel : BindableBase  
  8.     {  
  9.         #region Properties    
  10.         private bool _isButtonClicked;  
  11.         public bool IsButtonClicked  
  12.         {  
  13.             get { return _isButtonClicked; }  
  14.             set { SetProperty(ref _isButtonClicked, value); }  
  15.         }  
  16.   
  17.         private string _userName;  
  18.         public string UserName  
  19.         {  
  20.             get { return _userName; }  
  21.             set { SetProperty(ref _userName, value); }  
  22.         }  
  23.   
  24.         private DateTime _dob;  
  25.         public DateTime DOB  
  26.         {  
  27.             get { return _dob; }  
  28.             set  
  29.             {  
  30.                 SetProperty(ref _dob , value);  
  31.             }  
  32.         }  
  33.   
  34.         private string _age;  
  35.         public string Age  
  36.         {  
  37.             get { return _age; }  
  38.             set  
  39.             {  
  40.                 SetProperty(ref _age , value);  
  41.             }  
  42.         }  
  43.   
  44.         private bool _isNationalityIndian;  
  45.         public bool IsNationalityIndian  
  46.         {  
  47.             get { return _isNationalityIndian; }  
  48.             set { SetProperty(ref _isNationalityIndian, value); }  
  49.         }  
  50.   
  51.         private bool _isMale = false;  
  52.         public bool IsMale  
  53.         {  
  54.             get { return _isMale; }  
  55.             set  
  56.             {  
  57.                 SetProperty(ref _isMale, value);  
  58.             }  
  59.         }  
  60.   
  61.         private bool _isFeMale = false;  
  62.         public bool IsFemale  
  63.         {  
  64.             get { return _isFeMale; }  
  65.             set  
  66.             {  
  67.                 SetProperty(ref _isFeMale, value);  
  68.             }  
  69.         }  
  70.         public DelegateCommand<object> RegisterButtonClicked { getset; }  
  71.         #endregion  
  72.  
  73.         #region Constructor    
  74.         public MainWindowViewModel()  
  75.         {  
  76.             RegisterButtonClicked = new DelegateCommand<object>(RegisterUser);  
  77.         }  
  78.  
  79.         #endregion  
  80.  
  81.         #region Methods  
  82.         private void RegisterUser(object obj)  
  83.         {  
  84.             IsButtonClicked = true;  
  85.         }  
  86.         #endregion  
  87.   
  88.     }  

If I run this application, all the controls will be filled with a default value of their respective dataTypes. As follows:
 
 
What is the problem here?
  • Here, what if I don't want the user to see this useless information? Instead I want to show information, which really makes sense here.

    • Such as having a sensible date rather than 1/1/0001 or
    • No one with age 0 is going to the college or
    • And most of the users will be Indians, so I want (Indian)Nationality to be checked by default.
Solution - TargetNullValue
  • This is where we use TargetNullValue: TargetNullValue is set to thecontrol's bound property when the value of the bound property also known as source property is null for some reason.
  • In layman's terms, when the target is null, this property will be assigned.
  • Let's dig in to our code,

    • For UserName - as string UserName is null, it will display "Dow Jones" instead of showing empty text block. Note: string is already null so TargetNullvalue will be triggered.
      1. Text="{Binding UserName,TargetNullValue='Dow Jones'}"   
    • For Date of Birth, rather than showing date's default value, we are going to display today's date. Note: we can't set DateTime to null so have to make nullable DateTime.
      1. SelectedDate="{Binding DOB, TargetNullValue={x:Static sys:DateTime.Now}}"   
    • Minimum age criteria for admission is 18, so let's set TargetNullValue to 18. Note: we can't set int to null so have to make nullable int.
      1. Text="{Binding Age, TargetNullValue=18}"    
    • For Nationality: bool's default value is false, but we are setting TargetNullValue to true, as it is one of our requirements.  Note: we can't set the bool to null so have to make nullable bool.
      1. IsChecked="{Binding IsNationalityIndian,  TargetNullValue=True}"      
Finally, let's find out how it turned out to be.
 
 
Perfect! TargetNullValues have been successfully applied when source property was null for all 4 kinds of datatypes.
New Problem!!
  • That is cool, we can now handle a situation when source value is null and can make sense out of data with TargetNullValues. But what if there is a typo in bound property or our application fails to bind property for any reason. In such a case, we will have no data to display.
The Solution: FallBackValue
  • If your application is unable to find a bound property i.e. it fails to bind property then WPF will consider FallBackValue rather than displaying nothing.
  • In our application let's say we change the bound properties name and let's add FallBackValues to those controls.

    • Random_UserName instead of UserName
      1. Text="{Binding Random_UserName,FallbackValue='Dow Jones'}"
    • Random_DOB instead of DOB
      1. SelectedDate="{Binding Random_DOB, FallbackValue={x:Static sys:DateTime.Now}}" 
    • Random_Age instead of Age
      1. Text="{Binding Random_Age, FallbackValue=18}"     
    • Random_IsNationalityIndian instead of IsNationalityIndian
      1. IsChecked="{Binding Random_IsNationalityIndian,  FallbackValue=True}"   
 Let's check if it takes fallback values successfully!
 
 
Perfect... It works well.
Tip
 
We should always use both TargetNullValue & FallBackValue together, to have better control on error-prone code.
 
After following this tip your final code will look something like this,
 
MainWindow.xaml
  1. <Window x:Class="LearnWPF.MainWindow"    
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    
  4.         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"    
  5.         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"    
  6.         xmlns:local="clr-namespace:LearnWPF.ViewModel"    
  7.         xmlns:sys="clr-namespace:System;assembly=mscorlib"    
  8.         mc:Ignorable="d"    
  9.         Title="MainWindow" Height="250" Width="400">    
  10.     <Window.Resources>    
  11.         <local:MainWindowViewModel x:Key="VM" />    
  12.         <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>    
  13.     </Window.Resources>    
  14.     
  15.     <Grid DataContext="{Binding Source={StaticResource VM}}"    
  16.           HorizontalAlignment="Center">    
  17.         <Grid.RowDefinitions>    
  18.             <RowDefinition Height="Auto"/>    
  19.             <RowDefinition Height="Auto"/>    
  20.             <RowDefinition Height="Auto"/>    
  21.             <RowDefinition Height="Auto"/>    
  22.             <RowDefinition Height="Auto"/>    
  23.             <RowDefinition Height="Auto"/>    
  24.             <RowDefinition Height="5*"/>    
  25.         </Grid.RowDefinitions>    
  26.         <Grid.ColumnDefinitions>    
  27.             <ColumnDefinition Width="Auto"/>    
  28.             <ColumnDefinition Width="Auto"/>    
  29.         </Grid.ColumnDefinitions>    
  30.         <Label x:Name="LabelUserName"            
  31.                Content="User Name:"        
  32.                Margin="0 10 0 0"/>    
  33.         <Label x:Name="LabelDOB"             
  34.                Content="DOB:"            
  35.                Grid.Row="1"/>    
  36.         <Label x:Name="LabelAGE"             
  37.                Content="Age:"            
  38.                Grid.Row="2"/>    
  39.         <Label x:Name="LabelGender"             
  40.                Content="Gender:"            
  41.                Grid.Row="3"/>    
  42.         <Label x:Name="LabelNationality"             
  43.                Content="Nationality:"            
  44.                Grid.Row="4"/>    
  45.         <TextBox x:Name="TextBoxUserName"          
  46.                  Text="{Binding UserName, FallbackValue='Rikam', TargetNullValue='Palkar'}"        
  47.                  Height="20"            
  48.                  Width="150"           
  49.                  Margin="0 10 0 0"         
  50.                  Grid.Column="1"/>    
  51.         <DatePicker x:Name="DatePickerDOB"         
  52.                     SelectedDate="{Binding DOB, FallbackValue={x:Static sys:DateTime.Now}, TargetNullValue={x:Static sys:DateTime.Now}}"        
  53.                     DisplayDateStart="1/1/1990"        
  54.                     Width="150"        
  55.                     Grid.Column="1"        
  56.                     Grid.Row="1"/>    
  57.         <TextBox x:Name="TextBoxAge"       
  58.                  Text="{Binding Age, FallbackValue=18, TargetNullValue=18}"        
  59.                  Height="20"            
  60.                  Width="150"            
  61.                  Grid.Column="1"            
  62.                  Grid.Row="2"/>    
  63.     
  64.         <RadioButton x:Name="RadioButtonGenderMale"      
  65.                      IsChecked="{Binding IsMale, FallbackValue=False, TargetNullValue=False}"      
  66.                      Content="Male"      
  67.                      Margin="-110 8 0 0"      
  68.                      GroupName="Gender"      
  69.                      HorizontalAlignment="Center"      
  70.                      Grid.Row="3"    
  71.                      Grid.Column="1"/>    
  72.         <RadioButton x:Name="RadioButtonGenderFeMale"      
  73.                      IsChecked="{Binding IsFemale, FallbackValue=False, TargetNullValue=False}"      
  74.                      Content="Female"      
  75.                      Margin="30 8 0 0"      
  76.                      GroupName="Gender"      
  77.                      HorizontalAlignment="Center"      
  78.                      Grid.Row="3"    
  79.                      Grid.Column="1"/>    
  80.         <CheckBox x:Name="CheckBoxIsNationalityIndian"      
  81.                   IsChecked="{Binding IsNationalityIndian, FallbackValue=True, TargetNullValue=True}"      
  82.                   Margin="-50 8 0 0"      
  83.                   Content="Are you Indian?"      
  84.                   HorizontalAlignment="Center"      
  85.                   VerticalAlignment="Top"      
  86.                   Grid.Column="1"    
  87.                   Grid.Row="4"/>    
  88.         <Button x:Name="ButtonLogin"            
  89.                 Height="20"            
  90.                 Width="100"            
  91.                 Content="Register"            
  92.                 HorizontalAlignment="Center"            
  93.                 Margin="20 10 0 0"          
  94.                 Command="{Binding RegisterButtonClicked}"        
  95.                 Grid.Row="5"            
  96.                 Grid.ColumnSpan="2"/>    
  97.     
  98.         <TextBlock x:Name="TextBlockMessage"        
  99.                    Visibility="{Binding IsButtonClicked, Converter={StaticResource BooleanToVisibilityConverter}}"        
  100.                    Text="{Binding UserName, StringFormat='User: {0} is successfully registered!'}"        
  101.                    HorizontalAlignment="Center"        
  102.                    Margin="20 8 0 0"          
  103.                    Grid.Row="6"        
  104.                    Grid.ColumnSpan="2"/>    
  105.     </Grid>    
  106. </Window>    

Conclusion

  • We learned whatTargetNull & FallBack values are, and how & when to use them.
  • What the difference between them is.
  • How to use them with different types of datatypes.
  • I believe the given example was understandable as we have tried to cover the most. Please leave any suggestions with respect to FallbackValue and TargetNullValue.
  • Want to be a friend? Connect with me @

Thank you all, I wish you all the very best...
 
As always, Happy Coding...