2014-05-22 62 views
0

我正在製作一個應用程序,用戶可以通過某個路徑加載圖像。然後,加載的圖像的路徑被存儲,並且下一次用戶想要再次打開文檔時,則基於該路徑加載圖像。如果加載的圖像不存在,如何顯示默認的「圖像」?

但是,我想處理,以防萬一前者路徑無效(圖像移動/刪除),那麼它是不是犯了一個錯誤,但是,這種類型的對象表明:

enter image description here

我想知道是否有任何方法可以讓應用程序在沒有該圖像的情況下執行該操作。我的意思是,也許C#對於那種「缺失」圖像有一定的屬性?

謝謝。

P.S.而且,上面那個「失蹤」的圖片確實是一個「失蹤」的圖片。

回答

3

您可以創建一個自定義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文件路徑以上,而不是BitMapImageImageSource對象。它也會要求你提供一個默認的圖像來顯示。

2

您可以使用圖像控件的ImageFailed事件。

如果事件發生,在那裏設置錯誤圖像。

<Image src= ImageFailed="OnImageFailed" /> 
相關問題