0

On button click I want to change the canvas image(background image) to another image which is in a folder(images is the folder name). This is what I have tried:

    private void Button_Click_2(object sender, RoutedEventArgs e)
    {
        drawingCanvas.Children.Clear();
        ImageBrush imageBrush = new ImageBrush();
        imageBrush.ImageSource = new BitmapImage((new Uri(@"../Images/canvas.png", UriKind.Relative)));
        drawingCanvas.Background = imageBrush;

}

First I'm clearing the contents of the canvas, deleting the previous image. Now want to set the background to another image. error: URI not handled exception. Any solutions will be appreciated. Thanks.

lata
  • 91
  • 2
  • 2
  • 9
  • 1
    It looks like it can't find the image. Are you sure that the image path is accessible? – ChrisF Jan 07 '16 at 16:39
  • Does your Canvas contain an Image, or does it draw it's background using an Image? You are using `.Children.Clear` which suggests it contains an Image object, but then trying to draw the Background using an `ImageBrush`, which is something different. It sounds like what you actually want is to take the Image inside the Canvas and change it's Source property – Rachel Jan 07 '16 at 16:41
  • the image path is accessible. The image is basically blank on which the user can draw. First the user has the option to draw on an empty canvas or he can upload a map and draw on that. When he deletes the map then he should be able to draw again on an empty canvas, that's why I want to change the canvas background to blank. – lata Jan 07 '16 at 16:47
  • So on button click, the previous image is deleted and I want a new image to be set as the canvas background. – lata Jan 07 '16 at 16:48
  • Images is a folder in visual studio – lata Jan 07 '16 at 16:48

1 Answers1

0

An image resource is loaded by a Resource File Pack URI:

imageBrush.ImageSource = new BitmapImage(
    new Uri("pack://application:,,,/Images/canvas.png"));

In addition, the Build Actionof the image file has to be set to Resource, as shown in this answer.

Community
  • 1
  • 1
Clemens
  • 123,504
  • 12
  • 155
  • 268