如果属性路径中的父对象为空怎么办? [英] What if parent object in property path is null?
问题描述
如果属性路径中的父对象之一为null,我们如何控制会发生什么?例如:
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}" />
如果ActiveDrawing
为空怎么办?在这种情况下,我希望禁用此按钮,但是WPF使其保持启用状态.我尝试将FallBackValue
设置为null,如下所示:
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.
将TargetNullValue
设置为{x:Null}
也没有任何区别.
N.B. Setting TargetNullValue
to {x:Null}
also doesn't make a difference.
推荐答案
我目前已经设计了以下解决方法.
I have devised the following workaround for now.
-
创建一个名为
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>
将此对象用作您的FallbackValue:
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,由于一个唯一的原因,我不喜欢这种解决方案. FallbackValue
应该已经处理了这种情况.
TBH, I don't like this solution for one sole reason. FallbackValue
should have handled this situation.
这篇关于如果属性路径中的父对象为空怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!