图像控件,覆盖从 uri 下载图像的方法

Image control, override the method that download the image from an uri

我正在为 windows phone 8.1.

构建一个通用应用程序

我需要从 uri 下载图像,在 xaml 我通常会这样做

<Image Source="http://www.examlpe.com/img.png" />

但是这次我需要在http请求的header中添加一些参数,否则服务器不允许我下载图片。

我正在考虑使用依赖项 属性 扩展图像控件,该依赖项有一个带有所有正确 header 参数的 http 请求来下载图像。

我的问题是:

有没有更好的解决方案来实现这个结果?

编辑

这是我现在使用的代码

public class ImageUriExtension : DependencyObject
{
    public static readonly DependencyProperty ImageUriProperty = DependencyProperty.Register("ImageUri", typeof(string), typeof(ImageUriExtension), new PropertyMetadata(string.Empty, OnUriChanged));

    public static string GetImageUri(DependencyObject obj)
    {
        return (string)obj.GetValue(ImageUriProperty);
    }

    public static void SetImageUri(DependencyObject obj, string value)
    {
        obj.SetValue(ImageUriProperty, value);
    }

    private static async void OnUriChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var source = d as Image;
        var path = e.NewValue as string;
        var uri = new Uri(NetConfig.baseUrl + path);
        var stream = await RestClient.DownloadFile(uri);

        var bitmap = new BitmapImage();
        await bitmap.SetSourceAsync(stream);

        source.Source = bitmap; 
    }
}

这是 xaml

<Image local:ImageUriExtension.ImageUri="{Binding url}" />

是的,因为 <Image /> 是密封的,你不能从中导出。您最好的选择是完全按照您的指示使用附加属性对其进行扩展。另一种选择是使用行为,但没有意义。它不会 "better" 比附加的 属性 更有效。干得好。