你可以像这样在 Style 和 Converter 的帮助下做到这一点:
不透明度转换器:
using System;
using System.Globalization;
using System.Windows.Data;
namespace EnableButton
{
public class OpacityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (bool) value ? 1 : 0.5;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
您的 Xaml:
<Window x:Class="EnableButton.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:EnableButton"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:OpacityConverter x:Key="OpacityConverter"/>
<Style x:Key="DisableIcon" TargetType="Image">
<Setter Property="Opacity" Value="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Button}}, Path=IsEnabled, Converter={StaticResource OpacityConverter}}"/>
</Style>
</Window.Resources>
<StackPanel>
<Button Height="24" IsEnabled="False">
<Image Style="{StaticResource DisableIcon}" Source="Open_22.png"/>
</Button>
</StackPanel>
</Window>
现在,如果您更改按钮的 IsEnable 属性,您将看到结果。当父按钮在 OpacityConverter 中禁用时,我将 Image 的 Opacity 属性从 100% 更改为 50%,因此您可以根据需要修复此问题另一个数字。
更新
我对你的问题稍微思考了一下。我认为如果按钮被禁用,不仅可以更改图像的不透明度,而且可以将图像图片转换为单色。所以我找到了这个解决方案(添加对 Microsoft.Expression.Effects.dll 的引用并将 xmlns:ee="http://schemas.microsoft.com/expression/2010/effects" 添加到表单之前尝试):
<Window x:Class="EnableButton.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:EnableButton"
xmlns:ee="http://schemas.microsoft.com/expression/2010/effects"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style x:Key="DisableImageStyle" TargetType="Image">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Button}}, Path=IsEnabled}" Value="False">
<Setter Property="Opacity" Value="0.4"/>
<Setter Property="Effect">
<Setter.Value>
<ee:EmbossedEffect/>
<!--This effect is also looks nice-->
<!--<ee:MonochromeEffect/>-->
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<StackPanel>
<Button Height="40" IsEnabled="False">
<Image Style="{StaticResource DisableImageStyle}" Source="Open_22.png"/>
</Button>
</StackPanel>
</Window>
请注意,我现在不使用任何转换器!