我一直在浏览不同的帖子,试图弄清楚我的问题出在哪里。基本上,我在用户控件上有一个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。有什么想法吗?
var data = (new WebClient()).DownloadData("<your url>");
这样的代码吗?这应该会给你一个包含图像缓冲区的字节数组,只是为了看看下载是否正常工作。 - Clemens