在 WPF 中,由于空引用导致绑定失败时是否使用 FallbackValue?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33416567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:30:37  来源:igfitidea点击:

In WPF, is the FallbackValue used when the binding fails due to null references?

c#wpfdata-bindingdatatrigger

提问by sdgfsdh

My view-model exposes a list called MyListthat may be empty or null. I have an element that I would like hide based on this state. If MyListis empty or null, then the element should be collapsed. If it has elements then it should be shown.

我的视图模型公开了一个名为的列表MyList,该列表可能为空或null. 我有一个想要基于此状态隐藏的元素。如果MyList为空或null,则元素应折叠。如果它有元素,那么它应该被显示。

Here is my DataTrigger:

这是我的DataTrigger

<DataTrigger Binding="{Binding MyList.Count, FallbackValue=0}" Value="0">
    <Setter Property="Visibility" Value="Collapsed"></Setter>
</DataTrigger>
  • What happens to this DataTriggerwhen MyListis null?
  • Will it use the FallbackValueor will it fail?
  • Is this documented somewhere?
  • 恰巧这什么DataTrigger时候MyListnull
  • 它会使用FallbackValue还是会失败?
  • 这是在某处记录的吗?

回答by Nathan Kovner

The FallbackValueis used if the binding source path does not resolve, if the converter fails, or if the value is not valid for the property's type.

FallbackValue被使用,如果绑定的源路径不能解决,如果转换失败,或者如果值是无效的属性的类型。

It will not be used if nullis returned, unless nullis not valid for the property type. In this case the DataTriggerwill not be triggered. You can use TargetNullValuefor this case.

如果null返回,null则不会使用它,除非对于属性类型无效。在这种情况下DataTrigger将不会被触发。您可以TargetNullValue用于这种情况。

<DataTrigger Binding="{Binding MyList.Count, FallbackValue=0, TargetNullValue=0}" Value="0">
    <Setter Property="Visibility" Value="Collapsed"></Setter>
</DataTrigger>