在WPF中绑定图像源到URL

3

我一直在浏览不同的帖子,试图弄清楚我的问题出在哪里。基本上,我在用户控件上有一个Image标记,我想将其绑定到一个url。但是这并不起作用。我尝试使用一个ValueConverter返回BitmapImage(new Uri((string)value));,但是这也没有效果。唯一能做到的就是你不能绑定到一个url,你必须下载你想要绑定的图片。我不想下载我搜索到的所有图片。是否有一种方法可以实现这个任务而不必将图像下载到本地?我认为ValueConverter方法应该是最好的方法,通过返回一个BitmapImage。请帮忙吗?

public class MyViewModel
{
    private string _posterUrl;
        public string PosterUrl
        {
            get
            {
                //Get Image Url, this is an example and will be retrieved from somewhere else.
                _posterUrl = "http://www.eurobuzz.org/wp-content/uploads/2012/08/logo.jpg";
                return _posterUrl;    
            }
            set 
            { 
                _posterUrl = value;
                NofityPropertyChanged(p => p.PosterUrl);
            }
        }
}

这是我的值转换器:
public class BitmapImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if(value is string)
            return new BitmapImage(new Uri((string)value, UriKind.RelativeOrAbsolute));

        if(value is Uri)
            return new BitmapImage((Uri)value);

        throw new NotSupportedException();
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

这是我的XAML代码:
<Image Source="{Binding PosterUrl, Converter={StaticResource bitmapImageConverter}}" Width="100" Height="100" />

所以这个绑定到包含图像url的PosterUrl属性,并转换为BitmapImage。有什么想法吗?

请在上方找到我的代码。 - Donald N. Mafa
那应该完美地运作。也许请求该URL时未通过您的网络代理。您能在Internet Explorer中检索图像吗? - Clemens
即使没有转换器,字符串也会通过内置的TypeConverter自动转换为BitmapSource。你可以尝试(仅供测试)类似于var data = (new WebClient()).DownloadData("<your url>");这样的代码吗?这应该会给你一个包含图像缓冲区的字节数组,只是为了看看下载是否正常工作。 - Clemens
这行得通。我没有提到的另一件事是,这是一个Windows 8应用程序。在WinRT中,这种行为可能是不同的。请建议? - Donald N. Mafa
看起来不错。如果您有更多要发布的内容,可以简单地编辑您的问题。 - Clemens
显示剩余5条评论
2个回答

1

试一下

<Image Helpers:ImageAsyncHelper.SourceUri="{Binding Url, IsAsync=True}" x:Name="img" />

在哪里

using System;
using System.Windows;
using System.Windows.Data;
using System.Windows.Controls;

public class ImageAsyncHelper : DependencyObject {
    public static Uri GetSourceUri(DependencyObject obj){
        return (Uri)obj.GetValue(SourceUriProperty);
    }

    public static void SetSourceUri(DependencyObject obj, Uri value){
        obj.SetValue(SourceUriProperty, value);
    }

    public static readonly DependencyProperty SourceUriProperty =
        DependencyProperty.RegisterAttached("SourceUri",
            typeof(Uri),
            typeof(ImageAsyncHelper),
            new PropertyMetadata { PropertyChangedCallback = (obj, e) =>
                ((Image)obj).SetBinding(
                    Image.SourceProperty,
                    new Binding("VerifiedUri"){
                        Source = new ImageAsyncHelper{
                            _givenUri = (Uri)e.NewValue
                        },
                        IsAsync = true
                    }
                )
            }
        );

    private Uri _givenUri;
    public Uri VerifiedUri {
        get {
            try {
                System.Net.Dns.GetHostEntry(_givenUri.DnsSafeHost);
                return _givenUri;
            }
            catch (Exception) {
                return null;
            }
        }
    }
}

public Uri Url {
    get {
        return new Uri(SomeString, UriKind.Absolute);
    }
}

0
你是在尝试做这个吗?
<UserControl x:Class="WpfApplication1.UserControl1"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
<StackPanel Orientation="Vertical">
    <Image Height="100" Width="100" Source="{Binding}" />

    <Image Height="100" Width="100" Source="http://www.eurobuzz.org/wp-content/uploads/2012/08/logo.jpg"/>
</StackPanel>

代码后台:

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        this.DataContext = "http://www.eurobuzz.org/wp-content/uploads/2012/08/logo.jpg";
        InitializeComponent();
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接