AliTeo AliTeo - 12 days ago 5
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:



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

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

Answer

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:

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

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"];
}
Comments