c# – 将WPF中的图像源绑定到URL
发布时间:2020-12-15 21:45:57 所属栏目:百科 来源:网络整理
导读:我一直在浏览不同的帖子,试图弄清楚我的问题有什么问题.基本上我的用户控件上有一个 Image标签,而我想要绑定到一个url.但是这不起作用.我尝试使用返回BitmapImage的ValueConverter(new Uri((string)value)); 但这不起作用.我唯一能得到的是你不能绑定到一个u
我一直在浏览不同的帖子,试图弄清楚我的问题有什么问题.基本上我的用户控件上有一个
Image标签,而我想要绑定到一个url.但是这不起作用.我尝试使用返回BitmapImage的ValueConverter(new Uri((string)value));
但这不起作用.我唯一能得到的是你不能绑定到一个url,你必须下载你想要绑定的图像.我不想下载我seacrch的所有图像.是否需要在本地下载图像来完成此任务.我认为通过返回BitmapImage,ValueConverter方法将是最好的.请帮忙? 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); } } } 这是我的ValueConverter: 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,CultureInfo culture) { throw new NotSupportedException(); } } 这是我的XAML: <Image Source="{Binding PosterUrl,Converter={StaticResource bitmapImageConverter}}" Width="100" Height="100" /> 因此,它绑定到包含imageurl的PosterUrl属性,并将其转换为bitmapimage.有任何想法吗? 解决方法
试试吧
<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); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |