tags:

views:

448

answers:

2

I am trying to write a windows form application. I have some buttons and I need to change the image of the buttons according to the state of a variable. I put the images in the Resources folder and I’m trying to reach them like this:

Image im = Properties.Resources.green;

How can I reach this im value from all classes in my project just using "im" variable name?

+1  A: 

What you're looking for is a simple global variable, but they don't have those in C#. A simple alternative would be to create a class named MyImages (or whatever), and then make "im" a static public field, like this:

public class MyImages
{
    public static Image im = Properties.Resources.green;
}

Then, from anywhere in your project, you can access "im" with code like this:

Image newImage = MyImages.im;

Some programmers may recoil in horror from something like this, and insist on "dependency injection" or a proper Singleton, or making "im" private and creating a get/set public property, or something like that. However, if you literally need to access this Image from anywhere in your code, this is a simple and effective way to do it, and it accomplishes the goal of keeping the code to generate the Image in one place.

MusiGenesis
I would just fetch the image once and pass it to anything that needs it. That's **way** more flexible.
Joren
@Joren: well, OK, but pass it *how* and *from where*, exactly? In my code sample, the image is extracted from the resources exactly once, and is then available to any code within the project by calling "MyImages.im".
MusiGenesis
I'd have the Form fetch it in its constructor and store it in a private field. Then any event handlers defined in the form can use it directly. If a custom control that's a child of the form needs access to the image, I'd pass it to that control in its contructor. It's some passing around, but it makes sure you can reuse any part of the code with a different image without any extra changes being required.
Joren
Thank you for all your responses. I wrote the class like MusiGenesis said, and it works well. If there is any better way to do that, please let me know.
+1  A: 

You could try using the ResourceManager:

ResourceManager rm = new ResourceManager("items", Assembly.GetExecutingAssembly());

For more info look here

Colin