65.9K
CodeProject 正在变化。 阅读更多。
Home

ImageButton - 禁用时变为灰色

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2投票s)

2009年5月8日

CPOL

2分钟阅读

viewsIcon

39990

downloadIcon

700

提供了一个 ImageButton 的实现,该按钮在禁用时会变为灰色

引言

通常情况下,用户期望禁用的输入控件能够显示为禁用状态,即变灰。

不幸的是,.NET 提供的 ImageButton 没有暴露这种行为,所以我决定获取一个实现了这种行为的 ImageButton 实现。

然而,在浏览网络上的各种解决方案时,我发现的实现基本上都是扩展 ImageButton 以添加一个额外的 DisabledImageUrl 属性。

虽然这些方法有效,但它们要求每张图片都有一个禁用的版本,而许多图像库并不提供。
我想要的是一个控件,它仅仅使用现有的图片,并在禁用时将其变灰。

我开始研究 GDI+,并在进一步浏览网络后,发现了 这篇文章,它为我提供了将图像变灰所需的矩阵。

从那时起,剩下的就是创建扩展的 ImageButton 了。

Using the Code

ImageButtonExtended 的主要功能是下面的方法。

它根据按钮的启用状态分配要使用的图像 URL。

如果图像的禁用版本尚不存在,它会通过将上述矩阵应用于原始图像并以后缀保存来创建它。

private void AssignImageUrl()
  {
   //If enabled, we simply assign the enabled image URL
   if (base.Enabled)
   {
    this.ImageUrl = FileUtil.RemovePostfix(this.ImageUrl, DISABLED_POSTFIX);
    return;
   }

   //Get the URL of the disabled version of the image
   string disabledImageUrl = 
	FileUtil.InjectPostfix(this.ImageUrl, DISABLED_POSTFIX, true);

   //If the current image URL is already set to the proper value 
   //(which it will be if the button was initialised as disabled)
   //there is no need to go through the rest
   if (this.ImageUrl != disabledImageUrl)
   {
    //See if the disabled version of the image exists and if not, create it
    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;
   }
  }        

该实现使用了两个实用类,即

  • ImageUtil ,它封装了 GDI+ 代码以创建图像的单色版本
  • FileUtil ,它包含一些用于文件名修改的方法

由于许多开发人员都有类似的实用程序,我仅包含实现图像按钮所需的方法。

使用 ImageButtonExtended 与使用普通的 ImageButton 没有区别,并且没有额外的属性需要设置,因此所有现有的图像按钮都可以简单地替换为扩展版本。

关注点

ImageButtonExtended 有一些限制

  1. 如果 ImageUrl 设置为嵌入式资源,它将无法工作。
  2. 如果 ImageUrl 设置为外部 URL,它将无法工作,因为它会尝试将禁用的图像版本保存到原始图像的目录中。

克服这些限制留作读者练习。 :)

历史

  • 版本 1.0
© . All rights reserved.