代码之家  ›  专栏  ›  技术社区  ›  Amirshk

图像源绑定到丢失的文件

  •  2
  • Amirshk  · 技术社区  · 16 年前

    当绑定路径文件丢失时,如何显示默认图像?

    <Image  Source="{Binding DisplayedBook.ImagePath}" />
    

    我的解决方案:使用一个转换器,它检查图像是否存在并返回适当的路径。

    5 回复  |  直到 13 年前
        1
  •  6
  •   Dave Clemmer manu    13 年前

    如果不想从返回默认图像 ImagePath getter,另一种方法是返回null。

    public string ImagePath
    {
       get
       {
         return File.Exists(m_Path) ? m_Path : null;
       }
    }
    

    在xaml中使用绑定的targetnullvalue属性

    <Image  Source="{Binding DisplayedBook.ImagePath, TargetNullValue={StaticResource SomeImageResource}}" />
    
        2
  •  4
  •   John Bowen    16 年前

    如果您有与此xaml关联的代码隐藏(即不是模板),则可以在imagefailed事件上设置默认映像:

    <Image  Source="{Binding ImagePath}" ImageFailed="Image_ImageFailed" />
    

    处理者:

        private void Image_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {
            Image image = e.Source as Image;
            if (image != null)
                image.Source = new BitmapImage(new Uri("http://SomeDefaultImagePath.jpg"));
        }
    
        3
  •  1
  •   Oliver    16 年前

    我不使用wpf,所以我不知道是否存在这样的特殊功能。

    但我会在 DisplayedBook.ImagePath . 它检查文件是否存在,如果不存在,则返回到某个默认图像的路径。

        4
  •  1
  •   Archie    16 年前

    你也许可以这样做:

    获取路径中图像的路径。

    if (!File.Exists(path))
    {
        BitmapImage image = new BitmapImage();
    
        image.BeginInit();
        image.UriSource = new Uri(path);
        image.DecodePixelWidth = Convert.ToInt32(img.Width);
        image.EndInit();
    
        //Set the image corresponding to that bound
        this.img.Source = image;
    }
    
        5
  •  0
  •   Archie    16 年前

    您还可以添加 FallbackValue 属性,该属性获取或设置绑定无法返回值时要使用的值。

    推荐文章