[英]how to set image background in wpf
I am trying to set inactive buttons to have semi-transparent (ie greyed out) images. 我正在尝试将不活动的按钮设置为具有半透明(即变灰)的图像。 Yet for some reason the images become white/ yellow (as if on a bright background): 但是由于某些原因,图像变成白色/黄色(好像在明亮的背景上):
As you can see it's light yellow 如您所见,它是浅黄色
Possibly better annotated screenshot 注释可能更好的截图
Here are the XAML Styles: 这是XAML样式:
<Style x:Key="ToolButton" TargetType="{x:Type Button}" BasedOn="{x:Null}">
<Setter Property="Background" Value="#888"/>
<Setter Property="Padding" Value="10,2"/>
<Setter Property="BorderThickness" Value="0"/>
<Style.Resources>
<Style TargetType="Image">
<Style.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Opacity" Value="0.5"/>
</Trigger>
</Style.Triggers>
</Style>
</Style.Resources>
</Style>
<Style x:Key="ToolPanel" TargetType="{x:Type StackPanel}">
<Setter Property="Background" Value="#111"/>
<Style.Resources>
<Style TargetType="{x:Type Button}" BasedOn="{StaticResource ResourceKey=ToolButton}"/>
</Style.Resources>
</Style>
(StackPanel and buttons are dark for contrast, they are actually mean to be light grey) (为便于对比,StackPanel和按钮为黑色,实际上意味着它们为浅灰色)
What should I do to get the greyed out effect I want? 我应该怎么做才能获得想要的变灰效果?
The problem is the default Button
template: it changes its background based on the control's state, and that new background takes precedence over the one you're setting in your style. 问题是默认的Button
模板:它根据控件的状态更改背景,并且新背景优先于您在样式中设置的背景。
In this case, the brush for the 'Disabled' state is something like #F4F4F4
, or a very light gray. 在这种情况下,“禁用”状态的画笔类似于#F4F4F4
或非常浅的灰色。
The fix would be to declare a new Button
template. 解决方法是声明一个新的Button
模板。 For example: 例如:
<ControlTemplate TargetType="Button">
<!--Optional: Add border brush/thickness if you want a border-->
<Border x:Name="border" Background="{TemplateBinding Background}">
<ContentPresenter x:Name="contentSite" Margin="{TemplateBinding Padding}" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="False">
<!--Optional: Remove background when disabled-->
<!--Setter TargetName="border" Property="Background" Value="Transparent" /-->
<Setter TargetName="contentSite" Property="Opacity" Value="0.5" />
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="border" Property="Background" Value="#AAA" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="border" Property="Background" Value="#333" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
Note that with this version, you do not need the Image
style to change the Opacity
; 请注意,在此版本中,您不需要Image
样式即可更改Opacity
; it's taken care of in the Button
template. 在Button
模板中已进行了处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.