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

前端 未结 1 1517
故里飘歌
故里飘歌 2021-02-05 07:32

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

 


        
相关标签:
1条回答
  • 2021-02-05 08:10

    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

    0 讨论(0)
提交回复
热议问题