我在WPF中遇到了问题。我正在制作一个带有图像的删除按钮。但是,当禁用该按钮时,我想显示灰度图像。
我找到了Thomas Lebrun implementation,但我不想在我的程序中添加整个班级。相反,我试图以这种方式模仿行为:
BitmapImage img_Delete = new System.Windows.Media.Imaging.BitmapImage(new Uri("the png URI", UriKind.RelativeOrAbsolute));
ImageSource img_DeleteDisabled = null;
[...]
Button btDel = new Button() { Width = 20, Height = 20, ToolTip = "Delete", Margin = new Thickness(5), HorizontalAlignment = System.Windows.HorizontalAlignment.Right };
btDel.IsEnabled = isdeletable(obj);
if (!btDel.IsEnabled && (img_DeleteDisabled == null))
{
img_DeleteDisabled = new FormatConvertedBitmap(img_Delete, PixelFormats.Gray32Float, null, 0);
}
btDel.Content = (new System.Windows.Controls.Image()
{
Width = 16,
Height = 16,
HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch,
VerticalAlignment = System.Windows.VerticalAlignment.Stretch,
Source = btDel.IsEnabled ? img_Delete : img_DeleteDisabled
});
它表现得很好,除了..好吧,我会告诉你:
左侧启用,右侧禁用
正如您所见,Alpha通道已消失。我怎样才能将它整合回来?
答案 0 :(得分:0)
在评论的帮助下,我发现我正在考虑应用不透明蒙版的错误位置。
OpacityMask
应该应用于按钮,而不应用于图像。这是因为不透明度适用于整个图像而不是其来源。
出于这个原因,实现这个的正确方法是
btDel.Content = (new System.Windows.Controls.Image()
{
Width = 16,
Height = 16,
HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch,
VerticalAlignment = System.Windows.VerticalAlignment.Stretch,
Source = btDel.IsEnabled ? img_Delete : img_DeleteDisabled,
OpacityMask = new ImageBrush(img_Delete)
});
这样,蒙版就会应用于按钮图像。结果就是我需要的: