Reputation: 6284
How can i get the name of a local resource that has been assigned to a control property like BackgroundImage
?
For example, i have a button and i have set the BackgroundImage
property to a local resource image.
What i want, is at runtime to get the name of the local resource that has been assigned to BackgroundImage
of that button.
Upvotes: 0
Views: 1650
Reputation: 38875
If you look at your image:
you can see two things about the way your resources are handled. First, the return is a Bitmap
, so once assigned to a button or whatever, you would have a very hard time determining what it is from the image data. The second thing is that the identifiers are actually Properties
not just tokens or keys into a collection. The IDE generates these in your Resources.Designer.vb
file to provide access to the various resources. Here is the interface to get the bitmap of the French Flag from the resource designer file:
Friend ReadOnly Property FRFlag() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("FRFlag", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Yours will have things like Property error_button24BUTTON_DISABLED
. Like any other property, the name of the property is not part of the return, just the data associated with them.
Since what really matters is the state of the button, not the image being shown, and that Enabled state is very easy to evaluate, not much is lost just using an if statement:
If thisButton.Enabled Then
thisButton.BackGroundImage = My.Resources...
Else
thisButton.BackGroundImage = My.Resources...
End If
You would have had to do something like this to convert "True" for Enabled to "BUTTON_ENABLED" to create the resource "key" if it actually worked the way you thought it did, or was intent on getting it via Reflection.
There are several alternatives. One might be to write an ExtenderProvider
to provide various state images for the controls you are working with, subclass them or just use a local Dictionary/HashTable like an Extender would:
Friend Class ButtonImages
' ToDo: load these from My.Resources in the ctor for a given button
' ...
Private Property EnabledImage
Private Property DisabledImage
Public Function GetStateImage(b As Boolean) As Bitmap
If b Then
Return EnabledImage
Else
Return DisabledImage
End If
End Function
End Class
Private myBtnImgs As New Dictionary(of Button, ButtonImages)
thisButton.BackgroundImage = myBtnImgs(thisButton).GetStateImage(thisButton.Enabled)
It is more involved than a simple If statement, but comes close to what you seem to have been looking for.
Upvotes: 1