我有帮助方法将文件保存到独立存储并检索文件路径。
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.");
}
}
我的模特:
private string _imagePath;
public string ImagePath
{
get { return _imagePath; }
set
{
if (_imagePath != value)
{
NotifyPropertyChanging();
_imagePath = value;
NotifyPropertyChanged();
}
}
}
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:
<Image Source="Model.ImagePath" Height="300" Width="Auto"/>
我在stackoverflow上找到了一个转换器,但我无法弄清楚如何将它与我的代码一起使用。我想也许我不应该使用我的方法GetFilePath - 我应该制作一个从隔离存储中读取文件并将其传递给转换器的方法吗?
对不起,我还在学习C#并跳进MVVM,但对于隔离存储和转换器以及诸如此类的东西仍然不是很好。
感谢任何人的帮助。
答案 0 :(得分:0)
最直接的方法是加载二进制内容并将其分配给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();
}
}
完整样本也可用here。