wpf 按钮 IsEnabled 触发器不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12494045/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 05:25:33  来源:igfitidea点击:

Button IsEnabled Trigger does not work

c#wpfbuttontriggersisenabled

提问by Nick

I have a Buttonand its Style:

我有一个Button和它的风格:

<Button Name="MyBtn" Style="{StaticResource ButtonEnabledStyle}"
        IsEnabled="False" Opacity="1" />

<Style x:Key="ButtonEnabledStyle" TargetType="Button">
    <Style.Triggers>
        <Trigger Property="IsEnabled" Value="True" >
            <Setter Property="Opacity" Value="0.1" />
        </Trigger>
    </Style.Triggers>
</Style>

But when I enable the Button (MyBtn.IsEnabled = true) it does not change its Opacity. Why? How can I solve this problem? Thanks.

但是当我启用按钮 ( MyBtn.IsEnabled = true) 时,它不会改变它的不透明度。为什么?我怎么解决这个问题?谢谢。

回答by Julien Lebosquain

A local value set on the element (Opacity="1"in your code) will always take precedence over a style or style trigger value. Please have a look at Dependency Property Setting Precedence List.

在元素上设置的本地值(Opacity="1"在您的代码中)将始终优先于样式或样式触发器值。请查看Dependency Property Setting Precedence List

An easy fix is to set the default value on the style instead:

一个简单的解决方法是在样式上设置默认值:

<Style x:Key="ButtonEnabledStyle" TargetType="Button">
  <Setter Property="Opacity" Value="1.0" />
  <Style.Triggers>
    <Trigger Property="IsEnabled" Value="True" >
      <Setter Property="Opacity" Value="0.1" />
    </Trigger>
  </Style.Triggers>
</Style>