Search code examples
c#windows-10-universalbitmapimagestoragefilefileopenpicker

Why can change BitmapImage source only once?


Please, help is needed. In this code have to be stupid mistake but what it is? If I run this very simple code I can load and change bitmap image only once. At first time it runs ok but if I like to change the image again (press the button) the first image remains. Why?

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>

CODE

    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;
    }

This code doesn't have any extra check. It means the image 'ProfilePicture.jpg' have to be in a folder before running app. Code works well at first run but on the second run (press the button again and selecting new picture) cannot change output on screen even the source change in folder.


Solution

  • While creating BitmapImage set CreateOptions to IgnoreImageCache.

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