1
我正在爲windows phone 8.1構建一個通用應用程序。圖像控制,覆蓋從uri下載圖像的方法
我需要從一個URI下載的圖像,在XAML我一般做這樣的事情
<Image Source="http://www.examlpe.com/img.png" />
,但這個時候,我需要一些參數添加到HTTP請求頭,否則服務器沒有按不允許我下載圖像。
我想擴展圖像控件與具有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}" />
我認爲這是一個很好的解決方案。如果uri更改,也許可以添加'CancelationToken'來取消下載。 –