对于我自己,我创建了以下示例:
<!-- 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 using DataContext -->
<Grid DataContext="{StaticResource MyTestData}">
<Image Name="ImageNull" Width="100" Height="100" HorizontalAlignment="Left" VerticalAlignment="Bottom" Source="{Binding Path=NullString, TargetNullValue={StaticResource NullImage}}" />
<Image Name="ImageNotFound" Width="100" Height="100" HorizontalAlignment="Left" VerticalAlignment="Top" Source="{Binding Path=NotFoundString, FallbackValue={StaticResource ErrorImage}}" />
</Grid>
图像的路径,我在资源中宣布。图像存储在项目的根目录中。清单MyTestData
:
public class TestDataForImage : DependencyObject
{
public string NotFoundString
{
get
{
return (string)GetValue(NotFoundStringProperty);
}
set
{
SetValue(NotFoundStringProperty, value);
}
}
public static readonly DependencyProperty NotFoundStringProperty = DependencyProperty.Register("NotFoundString", typeof(string), typeof(TestDataForImage), new PropertyMetadata(""));
public string NullString
{
get
{
return (string)GetValue(NullStringProperty);
}
set
{
SetValue(NullStringProperty, value);
}
}
public static readonly DependencyProperty NullStringProperty = DependencyProperty.Register("NullString", typeof(string), typeof(TestDataForImage), new PropertyMetadata(""));
public TestDataForImage()
{
NotFoundString = "pack://application:,,,/NotExistingImage.png";
NullString = null;
}
}