用于按钮等场景,在禁用状态下变灰的图像。





5.00/5 (2投票s)
AutoGrayImage:一个图像类,当其被禁用时会变为灰度图。
下载 GrayImage.zip - 61.83 KB
引言
WPF的一个众所周知的缺陷是,禁用(工具栏或其他)按钮或菜单项的图像不会以灰度显示。 有三种常见的解决方法:- 使用触发器设置图像的
Opacity
。 - 设置图像的
Effect
。 - 使用自定义图像类。
使用代码
<Button> <my:AutoGrayImage Source2="/GrayImage;component/Images/Tulips.png" /> </Button>在XAML中,只需将你的
Image
替换为AutoGrayImage
,并设置Source2
属性,而不是Source
属性。 结果如下所示:
代码
你还应该将以下类添加到你的项目中: public class AutoGrayImage : Image
{
public AutoGrayImage()
{
IsEnabledChanged += new
DependencyPropertyChangedEventHandler(AutoGrayImage_IsEnabledChanged);
}
void AutoGrayImage_IsEnabledChanged(object sender,
DependencyPropertyChangedEventArgs e)
{
Source = IsEnabled?Source2:GrayedImage;
}
FormatConvertedBitmap GrayedImage = null;
public static readonly DependencyProperty Source2Property =
DependencyProperty.Register("Source2", typeof(BitmapSource),
typeof(AutoGrayImage), new PropertyMetadata(null,
OnSource2Changed));
/// <summary>
/// Sets the image to be grayed, or not.
/// </summary>
public BitmapSource Source2
{
get { return (BitmapSource)GetValue(Source2Property); }
set { SetValue(Source2Property, value); }
}
static void OnSource2Changed(DependencyObject sender,
DependencyPropertyChangedEventArgs e)
{
AutoGrayImage s = sender as AutoGrayImage;
if (s.Source2 == null)
{
s.GrayedImage = null;
}
else
{
s.GrayedImage = new FormatConvertedBitmap(s.Source2,
PixelFormats.Gray8, null, 0);
s.OpacityMask = new ImageBrush(s.Source2);
}
s.AutoGrayImage_IsEnabledChanged(s, new
DependencyPropertyChangedEventArgs());
}
}
我承认引入另一个Source
属性,即Source2
,并不是完全干净的做法。 然而,它似乎是在(整洁度/编写代码行数)比率方面最佳的选择。