通过URL下载图片,然后在C#中设置为按钮背景

Download Image via URL, then set it as a button background in C#

使用 VS 2013 并在 C# 中使用 Silverlight 开发 Windows Phone 8.1。

联系了一个 API 得到了一个 URL 让我查看图片,我想用那个 URL 下载图片,然后将其设置为背景一个按钮。

不太确定如何做到这一点。我是否必须将图片保存到内存,然后检索它并以某种方式将其设置为图像的背景?

我在这方面很迷路。

所以您需要做的是,创建一个 ImageBrush 对象并将其源 属性 加载为来自您想要拍照的 URL 的 BitmapImage,然后将 ImageBursh 设置为按钮对象的背景。

         private ImageBrush GetImage(){

            BitmapImage bi = new BitmapImage(new Uri("http://pic2.pbsrc.com/home/jan2015/winter.jpg"));

            var imageBrush = new ImageBrush
                {
                  ImageSource = bi
                };

            return imageBrush;
    }

然后在您的按钮单击方法中,或者如果您愿意,在页面构造函数中(在 ctor 中它不会工作,除非您使用 Async 和 Await 调用)将检索到的画笔作为背景。

   private void btn_Click(object sender, RoutedEventArgs e)
    {
        btn.Background = GetImage();
    }