窗口形式的这个 conde:
using (WebClient ownPicLoader = new WebClient())
pbOwnImage.Image = Image.FromStream(new MemoryStream(ownPicLoader.DownloadData("https://graph.facebook.com/" + _client.ClientNick + "/picture?width=200&height=200")));
窗口形式的这个 conde:
using (WebClient ownPicLoader = new WebClient())
pbOwnImage.Image = Image.FromStream(new MemoryStream(ownPicLoader.DownloadData("https://graph.facebook.com/" + _client.ClientNick + "/picture?width=200&height=200")));
在 WPF 中,您可以直接使用链接作为ImageSource
例子:
代码:
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
}
private string image;
public string Image
{
get { return image; }
set { image = value; NotifypropertyChanged("Image"); }
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Image = "http://icons.iconarchive.com/icons/chromatix/keyboard-keys/128/0-icon.png";
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifypropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
xml:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="252.351" Width="403.213" Name="UI" >
<Grid>
<StackPanel HorizontalAlignment="Left" Height="177" Margin="23,10,0,0" VerticalAlignment="Top" Width="191">
<Image Source="{Binding ElementName=UI, Path=Image, IsAsync=True}" Stretch="Uniform" />
<Button Click="Button_Click_1" Content="Get Image" />
</StackPanel>
</Grid>
</Window>
或者,您可以像在 winforms 应用程序中一样下载并显示图像。
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
}
private BitmapImage image;
public BitmapImage Image
{
get { return image; }
set { image = value; NotifypropertyChanged("Image"); }
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
using (WebClient ownPicLoader = new WebClient())
{
ownPicLoader.DownloadDataCompleted += (s, args) =>
{
var downloadImage = new BitmapImage();
downloadImage.BeginInit();
downloadImage.StreamSource = new MemoryStream(args.Result);
downloadImage.EndInit();
Image = downloadImage;
};
ownPicLoader.DownloadDataAsync(new Uri("http://icons.iconarchive.com/icons/chromatix/keyboard-keys/128/0-icon.png"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifypropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}