问题
How do we control what happens if one of the parent objects in the property path is null? For example:
<Button Command="{Binding ActiveDrawing.PrintCommand}" />
What if ActiveDrawing
is null? I want this button to be disabled in that case, but WPF keeps it enabled. I have tried setting FallBackValue
to null, like this:
<Button Command="{Binding ActiveDrawing.PrintCommand, FallbackValue={x:Null}}" />
but it doesn't make a difference. The button keeps enabled.
N.B. Setting TargetNullValue
to {x:Null}
also doesn't make a difference.
回答1:
I have devised the following workaround for now.
Create a new class named
NullCommand
:Public Class NullCommand Implements ICommand Public Event CanExecuteChanged As EventHandler Implements ICommand.CanExecuteChanged Public Sub Execute(parameter As Object) Implements ICommand.Execute End Sub Public Function CanExecute(parameter As Object) As Boolean Implements ICommand.CanExecute Return False End Function End Class
Create an instance of the class in the Resources section:
<Window.Resources> <vm:NullCommand x:Key="NullCommand" /> </RibbonGroup.Resources>
Use this object as your FallbackValue:
<Button Command="{Binding ActiveDrawing.PrintCommand, FallbackValue={StaticResource NullCommand}" />
Hurrah! It works. Whenever the binding property path fails for any reason, your button will be disabled.
TBH, I don't like this solution for one sole reason. FallbackValue
should have handled this situation.
来源:https://stackoverflow.com/questions/45119882/what-if-parent-object-in-property-path-is-null