我正在Windows Phone 7应用程序中构建我的第一个应用程序。我有一幅来自网络的图像,当单击该图像时,我导航到另一个页面。我的xaml代码是:
<Button Click="Image_Click" Name="image1" Margin="-33,-16,-26,-13">
<Button.Background>
<ImageBrush Stretch="Fill" ImageSource = "http://political-leader.vzons.com/ArvindKejriwal/images/icons/landing.png"/>
</Button.Background>
</Button>
我的.cs代码是
private void Image_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/AAP.xaml", UriKind.Relative));
}
现在的问题是我想存储图像,以便甚至可以在脱机时查看它。任何人都可以帮助我为此目的进行哪些修改。
这是有关如何执行此操作的示例。逻辑如下:
LoadImage
方法。LoadImage
方法将从Web下载该映像,并在下载完成后调用事件处理程序。DownloadCompleted
方法)将图像保存到隔离存储中,然后LoadImage
再次调用。下一步将参考第2点。您可能需要稍后对其进行改进,以实现MVVM和使用DataBinding。
参考:nickharris.net,geekchamp.com
string imageName = "myImage.jpg";
string imageUrl = "http://political-leader.vzons.com/ArvindKejriwal/images/icons/landing.png";
public MainPage()
{
InitializeComponent();
LoadImage();
}
private void LoadImage()
{
BitmapImage bi = new BitmapImage();
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
//load image from Isolated Storage if it already exist
if (myIsolatedStorage.FileExists(imageName))
{
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(imageName, FileMode.Open, FileAccess.Read))
{
bi.SetSource(fileStream);
imageBrushName.ImageSource = bi;
}
}
//else download image to Isolated Storage
else
{
WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(DownloadCompleted);
wc.OpenReadAsync(new Uri(imageUrl, UriKind.Absolute), wc);
}
}
}
private void DownloadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null && !e.Cancelled)
{
try
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(imageName);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(e.Result);
WriteableBitmap wb = new WriteableBitmap(bitmap);
// Encode WriteableBitmap object to a JPEG stream.
Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
fileStream.Close();
}
//after image saved to Iso storage, call LoadImage method again
//so the method will set imageBrush's ImageSource to image in Iso storage
LoadImage();
}
catch (Exception ex)
{
//Exception handle appropriately for your app
}
}
else
{
//Either cancelled or error handle appropriately for your app
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句