WPF Tips and Tricks 001: TargetNullValue and FallBackValue

In this series of WPF Tips and Tricks we will cover smaller but useful WPF features which would help in making our applications better. n this first part of WPF Tricks,we will examine two often ignored and less frequently properties of Binding class – TargetNullValue and FallBackValue.

TargetNullValue

Consider the following View and ViewModel.

View

<Label Content="UserName"/>
<TextBox Grid.Column="1" Text="{Binding UserName}"/>

<Label Grid.Row ="2"  Content="Date Of Birth"/>
<DatePicker Grid.Row="2" Grid.Column="1"  SelectedDate="{Binding DateOfBirth}"/>

ViewModel

public string UserName { get; set; }
public DateTime? DateOfBirth { get; set; } = null;

Both Source Properties have a default value of Null. In this scenario, when the View is loaded (assuming the values aren’t explicitly set elsewhere), one would get a screen as the following.

However, instead, if you wanted to fill in some default values for the control when the Source is null, you could make use of the TargetNullValue. This ensures that the Target Property of the control is set to a default value when the Source Property is null. Do note that this doesn’t have any impact on the Source Property.

Let us go ahead and modify our Xaml to include the TargetNullValue

<Label Content="UserName"/>
<TextBox Grid.Column="1" Text="{Binding UserName,TargetNullValue='Please enter name'}"/>

<Label Grid.Row ="2"  Content="Date Of Birth"/>
<DatePicker Grid.Row="2" Grid.Column="1"  SelectedDate="{Binding DateOfBirth, TargetNullValue={x:Static sys:DateTime.Now}}"/>


Alright, I know DateTime.Now is not the best value for default value when null, but I hope got the point. This would ensure your Form Controls would show some value when the bound Source property is null as illustrated in the following screenshot.

FallBackValue

Consider a situation when the Binding fails to determine the value based on the Source and Path. In such a situation the FallBackValue ensures there is a default backup value to displayed.

<Label Grid.Row ="4"  Content="Age"/>
<TextBox Grid.Row="4" Grid.Column="1"  Text="{Binding Age, FallbackValue=1}"/>

WPF’s fallback value provisions (both TargetNullValue and FallBackValue) are quite useful in providing better user experience to User when the data fails (other than validation issues).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s