How does WPF handle binding to the property of a n

2020-05-25 17:54发布

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条回答
不美不萌又怎样
2楼-- · 2020-05-25 18:18

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

查看更多
登录 后发表回答