我在 XAML 中声明了一个图像,但希望将 C# 中显示的图像设置为在独立存储中

本文关键字:图像 显示 存储 独立 希望 设置 声明 XAML 我在 一个 | 更新日期: 2023-09-27 18:32:30

我可以在我的 xaml 中这样声明我的图像

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanelx" Grid.Row="1" Margin="0,0,0,0">
    <Image x:Name="MyImage" Height="150" HorizontalAlignment="Left" Margin="141,190,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="200" />
</Grid>

我可以通过 .xaml 从独立存储加载我的图像.cs就像这样

void loadImage()
{
    // The image will be read from isolated storage into the following byte array
    byte[] data;
    // Read the entire image in one go into a byte array
    using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
    {
        using (IsolatedStorageFileStream isfs = isf.OpenFile("0.jpg", FileMode.Open, FileAccess.Read))
        {
            data = new byte[isfs.Length];
            isfs.Read(data, 0, data.Length);
            isfs.Close();
        }
    }
    MemoryStream ms = new MemoryStream(data);
    BitmapImage bi = new BitmapImage();
    bi.SetSource(ms);
    Image image = new Image();
    image.Height = bi.PixelHeight;
    image.Width = bi.PixelWidth;
    image.Source = bi;    
}

当我输入我的图像时。我找不到将其设置为我刚刚创建的图像的方法。你们中有人可以建议吗?

我在 XAML 中声明了一个图像,但希望将 C# 中显示的图像设置为在独立存储中

void loadImage() { // The image will be read from isolated storage into the following byte array
        byte[] data;
        // Read the entire image in one go into a byte array
        using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
        {
            using (IsolatedStorageFileStream isfs = isf.OpenFile("0.jpg", FileMode.Open, FileAccess.Read))
            {
                data = new byte[isfs.Length];
                isfs.Read(data, 0, data.Length);
                isfs.Close();
            }
        }
        MemoryStream ms = new MemoryStream(data);
        BitmapImage bi = new BitmapImage();
        bi.SetSource(ms);
        MyImage.Source = bi;    
    }
}

您需要设置MyImage.Source = bi; .就是这样

并进行一些重构:

void loadImage() { 
        BitmapImage bi = new BitmapImage();
        using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
        {
            using (IsolatedStorageFileStream isfs = isf.OpenFile("0.jpg", FileMode.Open, FileAccess.Read))
            {
                bi.SetSource(isfs);
            }
        }
        MyImage.Source = bi;    
    }
}