c# - 为什么BitmapImage源只能改一次?

标签 c# windows-10-universal bitmapimage storagefile fileopenpicker

拜托,需要帮助。在这段代码中必须是愚蠢的错误,但它是什么?如果我运行这个非常简单的代码,我只能加载和更改位图图像一次。第一次它运行正常,但如果我想再次更改图像(按下按钮),第一张图像仍然存在。为什么?

XAML

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <StackPanel>
        <Button x:Name="AddProfilePicture"  HorizontalAlignment="Center" Click="AddProfilePicture_Click">
            <Grid Width="200" Height="200">
                <Ellipse Width="200" Height="200">
                    <Ellipse.Fill>
                        <ImageBrush x:Name="ImageBrush_ProfilePicture" Stretch="UniformToFill"/>
                    </Ellipse.Fill>
                </Ellipse>
            </Grid>
        </Button>
    </StackPanel>
</Grid>

代码

    private async void AddProfilePicture_Click(object sender, RoutedEventArgs e)
    {
        FileOpenPicker profilePictureFilePicker = new FileOpenPicker();
        profilePictureFilePicker.ViewMode = PickerViewMode.Thumbnail;
        profilePictureFilePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
        profilePictureFilePicker.FileTypeFilter.Add(".jpg");
        StorageFile userSelectedProfilePicture = await profilePictureFilePicker.PickSingleFileAsync();
        //MAKE SURE U HAVE THIS FILE (ProfilePicture.jpg) IN FOLDER ALREADY....
        StorageFile destinationFileImage = await StorageFile.GetFileFromPathAsync(ApplicationData.Current.LocalFolder.Path + @"\" + "ProfilePicture.jpg");
        await userSelectedProfilePicture.CopyAndReplaceAsync(destinationFileImage);
        Uri profilePictureBitmapURI = new Uri(ApplicationData.Current.LocalFolder.Path + @"\" + "ProfilePicture.jpg");
        BitmapImage profilePictureBitmap = new BitmapImage(profilePictureBitmapURI);
        ImageBrush_ProfilePicture.ImageSource = profilePictureBitmap;
    }

此代码没有任何额外检查。这意味着图像“ProfilePicture.jpg”必须在运行应用程序之前位于文件夹中。代码在第一次运行时运行良好,但在第二次运行时(再次按下按钮并选择新图片)无法更改屏幕上的输出,即使文件夹中的源更改也是如此。

最佳答案

在创建 BitmapImage 时将 CreateOptions 设置为 IgnoreImageCache

var profilePictureBitmap = new BitmapImage(profilePictureBitmapURI) {CreateOptions = BitmapCreateOptions.IgnoreImageCache};

关于c# - 为什么BitmapImage源只能改一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39556421/

相关文章:

c# - 如何判断提供的文件是否确实是注册表配置单元

sqlite - 如何在 UWP 项目中使用预先设计好的 SQLite?

c# - 将 RenderTargetBitmap 转换为 BitmapImage

c# - 从 C# 在 TableCell 中插入图像

c# - 解压缩 PVRTC

c# - ASP.NET Core 中 AppSettings.json 内的 POCO 对象数组

xaml - 带有类型参数的页面

android - 空对象引用上的 Bitmap.getWidth()'

c# - 部分 View 不工作的 MVC3 Ajax 表单验证

UWP 页面生命周期