【问题标题】:How to show default "image" if the loaded image doesn't exist?如果加载的图像不存在,如何显示默认“图像”?
【发布时间】:2014-05-22 13:56:57
【问题描述】:

我正在制作一个用户可以通过特定路径加载图像的应用程序。然后,存储加载图像的路径,下次用户再次打开文档时,根据路径加载图像。

但是,我想处理一下,以防以前的路径无效(图像移动/删除),那么它不是犯了错误,但是,这种对象显示:

我想知道是否有任何方法可以让应用程序在没有该图像的情况下做到这一点。我的意思是,也许 C# 对那种“缺失”的图像有某种属性?

谢谢。

附:而且,上面那个“缺失”的图像确实是一个“缺失”的图像。

【问题讨论】:

    标签: c# wpf image io


    【解决方案1】:

    您可以创建一个自定义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-Event。

      如果引发事件,则在此处设置错误图像。

      <Image src= ImageFailed="OnImageFailed" />
      

      【讨论】:

        猜你喜欢
        • 2012-07-23
        • 2018-03-11
        • 1970-01-01
        • 2013-11-24
        • 2015-08-10
        • 1970-01-01
        • 1970-01-01
        • 2015-01-20
        • 2013-05-27
        相关资源
        最近更新 更多