[英]Setting an image source to a path from IsolatedStorage
I have helper methods for saving a file to isolated storage and retrieving the file path. 我有一些帮助方法,可以将文件保存到隔离存储中并检索文件路径。
public static string GetFilePath(string Name, string Directory)
{
try
{
using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isf.DirectoryExists(Directory))
{
string[] file = isf.GetFileNames(Path.Combine(Directory, Name));
return file.Length!=0?file[0]:null;
}
else
return null;
}
}
catch
{
MessageBox.Show("There was an error retrieving a file.");
return null;
}
}
public static void CreateFile(string Name, string Directory, Stream File)
{
try
{
using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isf.DirectoryExists(Directory))
{
isf.CreateDirectory(Directory);
}
if (isf.FileExists(Path.Combine(Directory, Name)))
{
isf.DeleteFile(Path.Combine(Directory, Name));
}
using (var stream = isf.CreateFile(Path.Combine(Directory, Name)))
{
File.CopyTo(stream);
File.Close();
}
}
}
catch
{
MessageBox.Show("There was an error creating the file.");
}
}
My model: 我的模特:
private string _imagePath;
public string ImagePath
{
get { return _imagePath; }
set
{
if (_imagePath != value)
{
NotifyPropertyChanging();
_imagePath = value;
NotifyPropertyChanged();
}
}
}
MainPageViewModel MainPageViewModel
private void LoadMainPhotos()
{
using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isf.FileExists("MainPhotos/MainPhoto"))
{
Model.ImagePath = HelperClasses.IsoStoreHelper.GetFilePath("MainPhoto", "MainPhotos");
}
}
}
private void photo_Completed(object sender, PhotoResult e)
{
HelperClasses.IsoStoreHelper.CreateFile("MainPhoto", "MainPhotos", e.ChosenPhoto);
LoadMainPhotos();
}
XAML: XAML:
<Image Source="Model.ImagePath" Height="300" Width="Auto"/>
I found a converter on stackoverflow, but I cannot figure out how to use it with my code. 我在stackoverflow上找到了一个转换器,但是我不知道如何在我的代码中使用它。 I'm thinking maybe I shouldn't use my method GetFilePath -- I should make a method for reading a file from isolated storage and passing it to the converter? 我在想也许我不应该使用我的GetFilePath方法-我应该制定一个从隔离存储中读取文件并将其传递给转换器的方法吗?
I'm sorry, I'm still learning C# and jumped into MVVM and still am not great with isolated storage and converters and whatnot. 对不起,我仍在学习C#,并跳入MVVM,但对于隔离存储,转换器和其他功能仍然不是很好。
Thanks anyone for the help. 感谢任何人的帮助。
The most straightforward way would be to load the binary content and assign it to a BitmapImage
entity (bound or not) and then push it as the source: 最直接的方法是加载二进制内容并将其分配给BitmapImage
实体(无论是否绑定),然后将其作为源推送:
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isfs = isf.OpenFile(strImageName, FileMode.Open, FileAccess.Read))
{
data = new byte[isfs.Length];
isfs.Read(data, 0, data.Length);
isfs.Close();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.