当按钮未启用时更改按钮背景

11

Button未启用时(IsEnabled == false),我需要更改其背景(例如使用SolidColorBrush)。
我应该如何做?

我需要通过XAML修改ButtonStyle,还是可以在程序中完成此工作?正确的XAML代码是什么,只更改未启用时的背景?

我尝试了以下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>

1
请查看此文章:http://www.infosysblogs.com/microsoft/2010/07/wpf_-_disabled_look_for_button.html - kmatyaszek
为什么这个不起作用?有人能解释一下吗? - SAT
2个回答

7
您可以通过编辑模板来更改背景。您可以在此处找到Button的默认模板。这里

IsEnabled触发器中,您可以简单地添加以下内容:

<Setter Property="Background" Value="{StaticResource DisabledBackgroundBrush}"/>

编辑: 那么试试这个方法;

<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>

只需根据您的需求进行更改。


这不是默认模板。我在哪里可以找到正确的模板? - Nick
你在找哪个版本?你可以在上面更改版本以获取其他版本。 - Eirik
我正在寻找默认版本。当我的按钮被禁用时,我只想更改背景。您提供给我的链接具有更改我的按钮默认样式的样式。请自行尝试。 - Nick
我是指.NET版本(即4.0 - http://msdn.microsoft.com/en-us/library/ms753328%28v=vs.100%29.aspx)。那么请尝试一下我刚刚添加的代码,应该可以工作。 - Eirik

-1

你可以使用样式触发器:

<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>

2
为什么要使用Image.Style?我需要更改Button的SolidColorBrush。 - Nick
使用Button.Background而不是Image.Source,并在Value中设置颜色(或特定刷子)。 - chameleon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接