How does WPF handle binding to the property of a null object?

早过忘川 提交于 2019-12-20 11:56:10

问题


I have a listBox using an itemTemplate that contains the following line:

<Image Source="{Binding MyProperty.PossiblyNullObject.UrlProperty}"/> 

Bound to this listBox is a model view collection that loads components of the items in the collection on a separate thread. The 'PossiblyNullObject' may not be set to a value when the xaml code is first rendered by the composition engine.

How does WPF handle this? Does it use a default value(no image source so no image) and continue on? Does it wait? Does it automatically detect when the value is initialized and rerenders with the new source? How does it not throw object null exceptions in the same way it would if I called 'MyProperty.PossiblyNullObject.UrlProperty' programmatically? How can I reproduce this functionality in my own code when I try to call it?

Thanks for any suggestions. I am embarrassingly new to WPF and I'm trying to tackle a problem out of my depth. The image load is a perf problem so I found a solution to load, decode, then freeze the image source on a background thread so it wouldn't lock up the UI. Unfortunately, I ran across this null exception problem when I tried replacing the image source binding with my solution that calls the same property. WPF somehow handles the possible null objects and I'd like to do it the same way to keep things clean.


回答1:


In BindingBase have two properties: TargetNullValue and FallbackValue.

TargetNullValue returns your value when the value of the source is null.

FallbackValue returns your value when the binding is unable to return a value.

Example of using:

<!-- xmlns:sys="clr-namespace:System;assembly=mscorlib" -->

<Window.Resources>
    <!-- Test data -->
    <local:TestDataForImage x:Key="MyTestData" />

    <!-- Image for FallbackValue -->
    <sys:String x:Key="ErrorImage">pack://application:,,,/NotFound.png</sys:String>

    <!-- Image for NULL value -->
    <sys:String x:Key="NullImage">pack://application:,,,/NullImage.png</sys:String>
</Window.Resources>

<Grid DataContext="{StaticResource MyTestData}">
    <Image Name="ImageNull"
           Width="100" 
           Height="100"
           Source="{Binding Path=NullString, TargetNullValue={StaticResource NullImage}}" />

    <Image Name="ImageNotFound"
           Width="100" 
           Height="100" 
           Source="{Binding Path=NotFoundString, FallbackValue={StaticResource ErrorImage}}" />
</Grid>

See this links, for more information:

BindingBase.TargetNullValue Property

BindingBase.FallbackValue Property



来源:https://stackoverflow.com/questions/21066931/how-does-wpf-handle-binding-to-the-property-of-a-null-object

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