您可以創建一個自定義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
對象。它也會要求你提供一個默認的圖像來顯示。