我们在项目中使用自定义图像作为按钮。我们通过一种风格应用它,但现在需要“禁用”按钮,并试图将图像换成新的。
第一个Trigger按预期工作100%。当按钮的IsEnabled == True时,按钮为“绿色”。当按钮的IsEnabled == False时,绿色被移除,前景颜色改变但灰色图像不会加载。
我错过了什么吗?
<Style TargetType="{x:Type Button}" x:Key="GreenGreyButton">
<Style.Triggers>
<Trigger Property="IsEnabled" Value="True">
<Setter Property="Background">
<Setter.Value>
<ImageBrush ImageSource="..\Images\UI\Buttons\green.png"/>
</Setter.Value>
</Setter>
<Setter Property="Foreground" Value="#FFA30046"/>
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Background">
<Setter.Value>
<ImageBrush ImageSource="..\Images\UI\Buttons\grey.png"/>
</Setter.Value>
</Setter>
<Setter Property="Foreground" Value="Gray"/>
</Trigger>
</Style.Triggers>
</Style>
答案 0 :(得分:2)
将图像作为内容添加到按钮&amp;改为使用DatatTrigger,如下所示:
<Button...
>
<StackPanel>
<Image>
<Image.Style>
<Style TargetType="Image">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsEnabled, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" Value="True">
<Setter Property="Source" Value="..\Images\UI\Buttons\green.png"/>
</DataTrigger>
<DataTrigger Binding="{Binding Path=IsEnabled, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" Value="False">
<Setter Property="Source" Value="..\Images\UI\Buttons\grey.png"/>
<Setter Property="Foreground" Value="Gray"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
</StackPanel>
</Button>
答案 1 :(得分:2)
遗憾的是,当IsEnabled
为false时,原生样式将覆盖所有设置(使用默认的灰色背景)。但是,你可以像这样重新模板化按钮:
<Style TargetType="{x:Type Button}" x:Key="GreenGreyButton">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border Background="{TemplateBinding Background}">
<ContentPresenter Content="{TemplateBinding Content}"
Margin="{TempateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="Background">
<Setter.Value>
<ImageBrush ImageSource="..\Images\UI\Buttons\green.png"/>
</Setter.Value>
</Setter>
<Setter Property="Foreground" Value="#FFA30046"/>
<Style.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Background">
<Setter.Value>
<ImageBrush ImageSource="..\Images\UI\Buttons\grey.png"/>
</Setter.Value>
</Setter>
<Setter Property="Foreground" Value="Gray"/>
</Trigger>
</Style.Triggers>
</Style>
答案 2 :(得分:0)
您需要为属性设置默认值
<Style TargetType="{x:Type Button}" x:Key="GreenGreyButton">
<Setter Property="Background">
<Setter.Value>
<ImageBrush ImageSource="..\Images\UI\Buttons\green.png"/>
</Setter.Value>
</Setter>
<Setter Property="Foreground" Value="#FFA30046"/>
<Style.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Background">
<Setter.Value>
<ImageBrush ImageSource="..\Images\UI\Buttons\grey.png"/>
</Setter.Value>
</Setter>
<Setter Property="Foreground" Value="Gray"/>
</Trigger>
</Style.Triggers>