WPF Textblock TargetNullValue not working?

SuicideSheep picture SuicideSheep · Mar 11, 2014 · Viewed 11.3k times · Source

I have a wpf textblock as below:

<TextBlock Text="{Binding [someViewModel].SomeVar.SomeSubVar.Name, 
                          TargetNullValue='-'}"/>

At my viewmodel side, I'll have my own logic that in the end, SomeVar.SomeSubVar will be null.

If I want to show a default value for this TextBlock I know I can declare and initiate SomeVar.SomeSubVar and assign default value into SomeVar.SomeSubVar.Name but I would like to use TargetNullValue instead. May I know which part is wrong?

Answer

Shawn Rakowski picture Shawn Rakowski · Mar 11, 2014

You might look at using FallbackValue http://msdn.microsoft.com/en-us/library/system.windows.data.bindingbase.fallbackvalue(v=vs.110).aspx in conjunction with TargetNullValue.

In order for TargetNullValue to work you must be able to evaluate the full path of [someViewModel].SomeVar.SomeSubVar.Name to null. If 'someViewModel', 'SomeVar', or 'SomeSubVar' are null then 'Name' can never be evaluated, and TargetNullValue won't apply.