如何在单击时更改矩形的图像

时间:2022-11-21 21:02:37

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

PresentationFramework.dll中发生未处理的“System.Windows.ResourceReferenceKeyNotFoundException”类型异常

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>

1 个解决方案

#1


0  

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.

您没有指定名为Closed.png的资源,只是将该名称的图像文件分配给Image控件的ImageSource属性。

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

你可能想要的是定义两个BitmapImage资源,如下所示:

<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

并像这样在XAML中使用它们

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

#1


0  

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.

您没有指定名为Closed.png的资源,只是将该名称的图像文件分配给Image控件的ImageSource属性。

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

你可能想要的是定义两个BitmapImage资源,如下所示:

<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

并像这样在XAML中使用它们

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