【问题标题】:When button isEnabled is false change background当按钮 isEnabled 为 false 时更改背景
【发布时间】:2015-05-25 02:25:45
【问题描述】:

我有一个带有按钮的 Itemscontrol 的 Itemscontrol。这样就形成了一个有 64 个按钮的矩阵。 每个按钮都绑定到一个 ViewModel。这些按钮有一个有颜色的日食。

一个按钮可以有两种状态。

1) ViewModel 为按钮中的日食提供颜色,然后是按钮IsEnabled=true
2) 按钮IsEnabled=false,按钮不再可点击。

我希望数字 2 具有透明背景(当按钮未启用时)。我解决了一些问题并得到了这个(参见 Pastebin 上的代码),但现在我的边界消失了,一切都是透明的。

如何让每个按钮的边框始终可见,因此不限于数字 1 和 2。

这是我的代码。我把它放在 Pastebin 上以节省空间。 巴斯宾:http://pastebin.com/4GHCW0y8 谢谢

【问题讨论】:

    标签: wpf xaml


    【解决方案1】:

    您的代码有几个问题:

    1. 您正在直接在按钮上设置 Background、BorderBrush 和 BorderThickness 属性,而不是在样式中使用 setter。以这种方式设置它们会覆盖样式所做的任何事情,因此您看不到样式触发器的效果。这是我指的那一行:

      <Button Style="{StaticResource MyButton2}" Command="{Binding PlaceStoneCommand}" Background="Transparent" BorderBrush="Black" BorderThickness="0.75"  Width="30" Height="30">
      

      从该行中删除 Background、BorderBrush 和 BorderThickness 属性,并改为在样式中创建设置器。另外请注意,您将默认设置为透明,因此即使进行此更改,您也只是在 IsEnabled 更改时在透明和透明之间切换。

    2. 您的样式覆盖了按钮的控件模板,并且没有使用模板中的 BorderBrush 或 BorderThickness 属性,因此在按钮上设置这些属性不会有任何效果。您可能希望为模板中定义的 Border 上的这些属性设置模板绑定。所以,你最终会得到一个看起来像这样的样式:

      <Style TargetType="{x:Type Button}" x:Key="MyButton2">
          <!-- Put default values here, or remove these if you want to use the existing button defaults -->
          <Setter Property="Background" Value="Transparent"/>
          <Setter Property="BorderBrush" Value="Black" />
          <Setter Property="BorderThickness" Value="1" />
          <Setter Property="Template">
              <Setter.Value>
                  <ControlTemplate TargetType="{x:Type Button}">
                      <Border Background="{TemplateBinding Background}"
                              BorderBrush="{TemplateBinding BorderBrush}"
                              BorderThickness="{TemplateBinding BorderThickness}">
                          <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                      </Border>
                  </ControlTemplate>
              </Setter.Value>
          </Setter>
          <Style.Triggers>
              <Trigger Property="IsEnabled" Value="False">
                  <Setter Property="Background" Value="Transparent"/>
                  <Setter Property="BorderBrush" Value="Black" />
                  <Setter Property="BorderThickness" Value="1" />
              </Trigger>
          </Style.Triggers>
      </Style>
      

    看看这些改变是否给你想要的结果。

    【讨论】:

    • 感谢您的帮助和解决方案。它工作得非常好。经过一些谷歌搜索后,我找到了另一个解决方案,它更短并且不适用于所有按钮。代码链接:pastebin.com/8qQH59pN
    猜你喜欢
    • 1970-01-01
    • 2014-11-10
    • 2015-10-04
    • 2019-12-21
    • 2011-07-16
    • 2013-03-31
    • 1970-01-01
    • 1970-01-01
    • 2011-12-09
    相关资源
    最近更新 更多