wpf 未启用时更改按钮背景
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14337602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change Button Background when is not enabled
提问by Nick
I need to change my Buttonbackground (as SolidColorBrush for example) only when it is not enabled (IsEnabled == false).
How can I do?
Button只有在未启用 ( IsEnabled == false)时,我才需要更改我的背景(例如 SolidColorBrush )。
我能怎么做?
Have I to modify the Button Styleusing the XAML or can I do this work programmatically? What is the correct XAML code, to change only the Background when it is not enabled?
我必须Style使用 XAML修改 Button还是可以以编程方式完成这项工作?什么是正确的 XAML 代码,在未启用时仅更改背景?
I tried the following XAML code but it has no effect:
我尝试了以下 XAML 代码,但没有效果:
<Button>
<Button.Style>
<Style TargetType="Button">
<Style.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Background" Value="Red"></Setter>
</Trigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
回答by Eirik
You can change the background by editing the template. You'll find the default template for Buttonhere.
您可以通过编辑模板来更改背景。您将在Button此处找到默认模板。
In the trigger for IsEnabledyou can simply add something like this:
在触发器中,IsEnabled您可以简单地添加如下内容:
<Setter Property="Background" Value="{StaticResource DisabledBackgroundBrush}"/>
EDIT: Try this instead then;
编辑:然后试试这个;
<Window.Resources>
<Style TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="Overlay" CornerRadius="2">
<ContentPresenter/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="false">
<Setter TargetName="Overlay" Property="Background" Value="Red"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<StackPanel>
<Button Content="Button" IsEnabled="False"/>
</StackPanel>
Just change it to suit your needs.
只需更改它以满足您的需求。
回答by Echilon
You can use a Style trigger:
您可以使用样式触发器:
<Image.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding IsEnabled}" Value="False">
<Setter Property="Image.Source" Value="pack://application:,,,/disabled.png" />
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>

