要吐槽一下,WINPHONE的开发资料真的少的可怜(不过MSDN上面基本已经可以了,我说的是整个的开发氛围)。
下面这个代码做的只是下载一张图片然后在界面上面显示出来,功能非常简单,不过代码知其然不知其所以然,回来再自己看看。
下面是XAML代码:
<phone:PhoneApplicationPage
x:Class="PhoneApp2.MainPage"
Loaded="PhoneApplicationPage_Loaded"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot 是包含所有页面内容的根网格-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Image Name="MyPic" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Stretch="None"/>
</Grid>
</phone:PhoneApplicationPage>
下面是CS文件:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PhoneApp2.Resources;
using System.IO;
using System.Diagnostics;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace PhoneApp2
{
public partial class MainPage : PhoneApplicationPage
{
private const String URL_API = "http://www.ray-joy.com/UploadFiles/clubfiles/2013-06/2013063007350484904.jpg";
// 构造函数
public MainPage()
{
InitializeComponent();
// 用于本地化 ApplicationBar 的示例代码
//BuildLocalizedApplicationBar();
}
private void Download(String uri)
{
System.Net.WebClient client = new System.Net.WebClient();
client.OpenReadAsync(new Uri(uri));
client.OpenReadCompleted += new System.Net.OpenReadCompletedEventHandler(webclient_openReadCompleted);
}
private void webclient_openReadCompleted(object sender, System.Net.OpenReadCompletedEventArgs e)
{
using (Stream s = e.Result)
{
byte[] data = new byte[s.Length + 1];
s.Read(data , 0 , data.Length);
BitmapImage image = new BitmapImage();
MemoryStream ms = new MemoryStream(data);
image.SetSource(ms);
MyPic.Source = image;
}
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
Download(URL_API);
}
}
}