将图像从隔离存储加载到可观察集合不起作用
本文关键字:观察 集合 不起作用 加载 图像 隔离 存储 | 更新日期: 2023-09-27 18:23:42
我正在从应用程序中的独立存储设置加载图像路径。
[DataMember]
public string entryImage = "";
[DataMember]
public string EntryImage
{
get { return entryImage; }
set { entryImage = value; }
}
使用helper类将图像存储到隔离的存储文件中。
public static void SaveImage(Stream imageStream, string directory, string filename)
{
try
{
string path = System.IO.Path.Combine(directory, filename);
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isoStore.DirectoryExists(directory)) isoStore.CreateDirectory(directory);
using (var writeStream = isoStore.CreateFile(path))
{
byte[] buffer = new byte[32768];
while (true)
{
int read = imageStream.Read(buffer, 0, buffer.Length);
if (read <= 0)
return;
writeStream.Write(buffer, 0, read);
}
}
}
}
// Catch exception if unable to save the image
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
这是我存储到Observelecollection 的图像路径的部分
MyDiaryItem _saveItems = new MyDiaryItem();
_saveItems.EntryNotes = InputText.Text;
_saveItems.EntryDate = date.ToString();
_saveItems.EntryImage = AppHelper.ImageDirectory + AppSettings.ImageFilename;
其中MyDiaryItem是可观察的集合
public ObservableCollection<MyDiaryItem> diaryItems = null;
隔离存储保存和加载
void LoadSettings()
{
if (settings.Contains("DiaryItems"))
{
diaryItems = new ObservableCollection<MyDiaryItem>((List<MyDiaryItem>)settings["DiaryItems"]);
}
}
void SaveSettings()
{
//settings["DiaryItems"] = diaryItems.ToList();
if (diaryItems.ToList() != null)
{
settings.Clear();
settings.Add("DiaryItems", diaryItems.ToList());
settings.Save();
}
}
这是图像源的xaml代码
<ListBox toolkit:TiltEffect.IsTiltEnabled="true" Name="AllEntriesList"
Margin="0,0,-12,0"
SelectionChanged="AllEntriesList_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="0,0,0,17">
<Image Source="{Binding EntryImage}" Height="100" Width="100" Stretch="Fill" Margin="12,0,9,0" />
<StackPanel Margin="0,0,0,17" Width="350" Height="Auto">
<TextBlock Text="{Binding EntryLocation}" TextWrapping="Wrap" Style="{StaticResource PhoneTextLargeStyle}" />
<TextBlock Text="{Binding EntryNotes}" TextWrapping="Wrap" Style="{StaticResource PhoneTextNormalStyle}" />
<TextBlock Text="{Binding EntryDate}" TextWrapping="Wrap" Style="{StaticResource PhoneTextSubtleStyle}" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我想了解如何使用从隔离存储中检索的图像路径来在日记项列表中显示图像。
我正在像这样加载OnNavigatedTo函数中的所有日记项。
AllEntriesList.ItemsSource=app.diaryItems;
我可以在diaryItems列表中看到正确填充的图像名称。我想在日记项目列表中显示图像。如何做到这一点?
<Image Source="{Binding EntryImage}" Height="100" Width="100" Stretch="Fill" Margin="12,0,9,0" />
您正在将字符串绑定到图像源。尝试将其绑定到BitmapSource
您可以很容易地从流中获取BitmapSource。例如:
BitmapSource CreateSource(Stream stream)
{
return source = PictureDecoder.DecodeJpeg(stream);
}