9

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?

SuicideSheep
  • 5,260
  • 19
  • 64
  • 117

2 Answers2

21

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.

Shawn Rakowski
  • 5,644
  • 2
  • 27
  • 29
4

The Binding's TargetNullValue property is displayed in the TextBlock if the [somveViewModel].SomeVar.SomeSubVar.Name property is null. It doesn't cane the value of the [somveViewModel].SomeVar.SomeSubVar.Name property. It effectively sets up an equivalency between null and the TargetNullValue property's value.

See this question for a good explanation.

So my advice is if you want to have a non-null default value, you need to set it in the view model.

Community
  • 1
  • 1
Tony Vitabile
  • 8,298
  • 15
  • 67
  • 123
  • This is what appears to happen, however this is not explained at all in the linked question. In fact, there are a lot of confusing answers and comments posted on that question. – Tim Pohlmann Apr 04 '16 at 11:52
  • I made a new question regarding TargetNullValue: http://stackoverflow.com/questions/36402291/why-does-targetnullvalue-update-nullable-source – Tim Pohlmann Apr 06 '16 at 07:07