Bind Image Source in WPF to a Url

2019-04-10 22:22发布

问题:

I having been browsing around different posts trying to figure out what is wrong with my issue. Basically I have a Image tag on my user control, and the Source I would like to bind to a url. However this does not work. I have tried using a ValueConverter that returns BitmapImage(new Uri((string)value)); but this does not work. The only thing I have been able to get is that you cannot bind to a url and that you have to download the image you want to bind. I do not want to download all images I seacrch. Is there a work around to achieving this task with out having to download the image locally. I thought the ValueConverter method would have been the best by return a BitmapImage. Please help?

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);
            }
        }
}

This is my 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, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

This is my XAML:

<Image Source="{Binding PosterUrl, Converter={StaticResource bitmapImageConverter}}" Width="100" Height="100" />

So this is binding to the PosterUrl property that contains the imageurl and this is converted to a bitmapimage. Any ideas?

回答1:

Try it

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

Where

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;
            }
        }
    }
}

And

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


回答2:

Are you trying to do this ?

<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>

Code behind :

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