Introduction
Users in general expect that input controls that are disabled appear so, i.e. are greyed out.
Unfortunately the ImageButton
that ships with .NET does not expose this behavior, so I decided to get a hold of an ImageButton
implementation that did.
However browsing various solutions on the net, I only came up with implementations that in essence extended the ImageButton
to have an extra DisabledImageUrl
property.
While these work fine, they do require that every image have a disabled version, which many image libraries do not.
So what I wanted was a control that simply used the existing image and greyed it out when disabled.
I began looking into GDI+ and after browsing the web some more, I came across this article that provided me with the proper matrix to use for greying out an image.
From there, all that remained was creating the extended ImageButton
.
Using the Code
The main functionality of the ImageButtonExtended
is the below method.
It assigns the image URL to use based on the enabled state of the button.
If the disabled version of the image does not yet exist, it creates it by applying the aforementioned matrix to the original image and saving that with a postfix.
private void AssignImageUrl()
{
if (base.Enabled)
{
this.ImageUrl = FileUtil.RemovePostfix(this.ImageUrl, DISABLED_POSTFIX);
return;
}
string disabledImageUrl =
FileUtil.InjectPostfix(this.ImageUrl, DISABLED_POSTFIX, true);
if (this.ImageUrl != disabledImageUrl)
{
string disabledImageFile = this.Context.Server.MapPath(disabledImageUrl);
if (!File.Exists(disabledImageFile))
{
string activeImageFile = this.Context.Server.MapPath(this.ImageUrl);
var img = ImageUtil.MakeMonochrome(activeImageFile);
img.Save(disabledImageFile);
}
this.ImageUrl = disabledImageUrl;
}
}
The implementation makes use of two utility classes, namely:
ImageUtil
which encapsulates the GDI+ code to create the monochrome version of an imageFileUtil
which contains a few methods for filename modification
Since many developers have similar utilities of their own, I only included the methods needed for the implementation of the image button.
Using the ImageButtonExtended
is no different from using the normal ImageButton
, and there are no extra properties to set so all existing image buttons can simply be replaced by the extended version.
Points of Interest
The ImageButtonExtended
does have a few limitations:
- It will not work if the
ImageUrl
is set to an embedded resource. - It will not work if the
ImageUrl
is set to an external URL, since it will try to save the disabled image version to the directory of the original image.
Overcoming these limitations is left as an exercise to the reader. :)
History