您可以创建一个自定义Converter 来为您执行此操作。为您添加一个属性,以便能够设置默认的Image 路径:
[ValueConversion(typeof(string), typeof(ImageSource))]
public class EmptyImageToImageSourceConverter : IValueConverter
{
/// <summary>
/// Converts an empty string value into the DefaultImagePath property value if it exists, or a DependencyProperty.UnsetValue otherwise.
/// </summary>
public string DefaultImagePath { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || targetType != typeof(ImageSource)) return DependencyProperty.UnsetValue;
string imagePath = value.ToString();
return imagePath.IsNullOrEmpty() ? DefaultImagePath.IsNullOrEmpty() ? DependencyProperty.UnsetValue : DefaultImagePath : imagePath;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}
那么你可以这样使用它:
<Converters:EmptyImageToImageSourceConverter x:Key="EmptyImageToImageSourceConverter"
DefaultImagePath="pack://application:,,,/AppName;component/Images/DefaultImage.png" />
请注意,此 Converter 与上述类似的 string 文件路径一起使用,而不是 BitMapImage 或 ImageSource 对象。它还需要您提供要显示的默认图像。