What if parent object in property path is null?

倾然丶 夕夏残阳落幕 提交于 2019-12-12 03:55:01

问题


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.

  1. 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
    
  2. Create an instance of the class in the Resources section:

    <Window.Resources>
      <vm:NullCommand x:Key="NullCommand" />
    </RibbonGroup.Resources>
    
  3. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!