c# - 如何从独立存储中获取图像

标签 c# silverlight windows-phone-7 isolatedstorage

我有这个 XAML

<ListBox Margin="0,0,-12,0" ItemsSource="{Binding Items}" Name="list">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" Margin="0,0,0,17">
                <!--Replace rectangle with image-->
                <Image Height="100" Width="100" Source="{Binding Img}" Margin="12,0,9,0"/>
                <StackPanel Width="311">
                    <TextBlock  Text="{Binding Pos}"/>
                </StackPanel>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

在代码中:

using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
    IsolatedStorageFileStream isoStoreStream = isoStore.OpenFile("chart.xml", FileMode.Open);
    using (StreamReader reader = new StreamReader(isoStoreStream))
    {
        XElement xml = XElement.Parse(reader.ReadToEnd());
        var list = from var in xml.Descendants("Pos")
            select new Single
            {
                Pos = Int32.Parse(var.Attribute("id").Value),
                Img = how read from isolated storage the image id.jpg?
            };

public class Single
{
    public int Pos { set; get; }
    public ??? Img { set; get; }
}

我已经将图像保存到独立存储中,但问题是:如何从独立存储中读取名称为 id.jpg(1.jpg, 2.jpg, 3.jpg...) 的图像?

最佳答案

在您的 Single 类中,Img 属性应为 ImageSource 类型。要设置此属性(从isolatedStorage读取图像),您可以执行以下操作:

private ImageSource getImageFromIsolatedStorage(string imageName)
{
    BitmapImage bimg = new BitmapImage();

    using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
    {
        using (IsolatedStorageFileStream stream = iso.OpenFile(imageName, FileMode.Open, FileAccess.Read))
        {
            bimg.SetSource(stream);
        }
    }
    return bimg;
}

然后在您的代码片段中:

using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
    IsolatedStorageFileStream isoStoreStream = isoStore.OpenFile("chart.xml", FileMode.Open);
    using (StreamReader reader = new StreamReader(isoStoreStream))
    {
        XElement xml = XElement.Parse(reader.ReadToEnd());
        var list = from var in xml.Descendants("Pos")
            select new Single
            {
                Pos = Int32.Parse(var.Attribute("id").Value),
                Img = getImageFromIsolatedStorage(string.Format("{0}.jpg", Pos));
            };

关于c# - 如何从独立存储中获取图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5900315/

相关文章:

c# - 使用 c# 的亚马逊市场网络服务 (amazon mws)

c# - 像 Unity3d 中的 3ds Max 一样缩放到鼠标位置

c# - 给定一个已连接且准备就绪的 DiscordSocketClient 和一个 Discord Channel Id,如何向该 channel 发送消息?

windows-phone-7 - 将传感器数据保存到本地计算机进行分析的最佳方法是什么?

C# - 命名设计模式

.net - 使用 Expression Encoder SDK 确定媒体是否需要转码

c# - windows phone 7开发的MVVM框架推荐

silverlight - 将前景转换器添加到 xaml 中的 DatagridTextColumn

c# - 如何将 GestureListener 处理程序添加到 silverlight 中的 cs 代码中的控件?

c# - 为什么我的用户控件会导致 Visual Studio 崩溃?