AliTeo AliTeo - 4 months ago 26
C# Question

How to change the image of a rectangle when clicked on it

I am writing a puzzle game where the player tries to escape the room but I encountered a problem. I am trying to change the image of a rectangle named "door" when clicked. But it doesn't change and gives a runtime error.

An unhandled exception of type 'System.Windows.ResourceReferenceKeyNotFoundException' occurred in PresentationFramework.dll

C# Code:

private void Rectangle_MouseDown(object sender, MouseButtonEventArgs e)
ImageBrush ib = new ImageBrush();
ib.ImageSource = (ImageSource)Resources["openImage"];

XAML Code:

<BitmapImage x:Key="openImage" UriSource="açık.png" />
<BitmapImage x:Key="closedImage" UriSource="Kapalı.png" />

<Rectangle x:Name="door" HorizontalAlignment="Left" Height="230" Margin="211,10,0,0" VerticalAlignment="Top" Width="100" MouseDown="Rectangle_MouseDown">
<ImageBrush Stretch="None"/>
<ImageBrush ImageSource="{StaticResource closedImage}"/>


You did not specify a resource named Closed.png, but just assigned an image file of that name to the ImageSource property of an Image control.

What you probably want is to define two BitmapImage resources like this:

    <BitmapImage x:Key="openImage" UriSource="Open.png" />
    <BitmapImage x:Key="closedImage" UriSource="Closed.png" />

and use them in XAML like this

<ImageBrush ImageSource="{StaticResource closedImage}"/>

and in code like this:

var fill = door.Fill as ImageBrush;

if (fill.ImageSource == (ImageSource)Resources["closedImage"])
    fill.ImageSource = (ImageSource)Resources["openImage"];