Luca
Luca

Reputation: 1826

WPF nested property binding not working if parent property is null

I have the following situtation:

<DatePicker IsEnabled="{Binding ParentObject.EditAvailable}"

Now if I set ParentObjectto nullin my ViewModel which is also the DataContext the IsEnabled Property on the DatePicker will be set to true

The binding is working completely correct for all instances if the ParentObject is properly set.

But I don't really get that behavior in WPF.

A workaround would be using:

<DatePicker IsEnabled="{Binding ParentObject.EditAvailable, FallbackValue=False}"

So now if the ParentObject is set to null via my ViewModel, the IsEnabled property on the DatePicker returns false.

Is there anything I can do without setting the FallbackValue on each of my controls in my project? It's already huge and I need to find a solution to have it somehow as default behavior that if the ParentObject is null, that there is a default value set default(bool), default(string) etc etc.

Any help is much appreciated.

Upvotes: 1

Views: 731

Answers (3)

Robin Bennett
Robin Bennett

Reputation: 3231

You can set IsEnabled on the panel or grid that contains the controls, and it will affect all controls it contains.

<StackPanel IsEnabled="{Binding ParentObject.EditAvailable, FallbackValue=False}">
    <DatePicker />
    <DatePicker />
    <DatePicker />
</StackPanel>

Upvotes: 2

ASh
ASh

Reputation: 35681

If binding Path is always the same, then you can use default style for DatePicker:

<Style TargetType="DatePicker">
  <Setter Property="IsEnabled" Value="{Binding ParentObject.EditAvailable, FallbackValue=False}"/>
</Style>

Upvotes: 1

mm8
mm8

Reputation: 169200

Is there anything I can do without setting the FallbackValue on each of my controls in my project?

No, not apart from replacing each binding with a custom one that sets the FallbackValue by default. See this answer for an example.

You will still have to replace {Binding with {local:YourBinding everywhere.

Upvotes: 1

Related Questions