【问题标题】:WPF - change Button controltemplate background when Command.CanExecute is falseWPF - 当 Command.CanExecute 为 false 时更改按钮控件模板背景
【发布时间】:2015-10-14 08:37:50
【问题描述】:

场景: 当使用按钮的默认实现时,以下功能有效:

当 canExecute 命令为真时 -> 按钮启用且按钮背景不改变。

当 CanExecute 命令为 false -> 按钮被禁用且背景为“灰色”。

但是当使用Button ControlTemplate 样式并且CanExecute 为false -> 按钮按预期被禁用但背景没有改变。

如何更改控件模板按钮的背景?

图片: https://onedrive.live.com/redir?resid=3A8F69A0FB413FA4!125&authkey=!ALh_kjfxMMNzhSY&v=3&ithint=photo%2cpng

Control Template: 

 <!--button-->
    <ControlTemplate x:Key="ButtonTemplate" TargetType="{x:Type Button}">

        <Border x:Name="border" CornerRadius="0" Background="Green"  BorderBrush="#FF06A6F0"  BorderThickness="1" Opacity="1"  Width="147" Height="50" >
            <ContentPresenter x:Name="contentPresenter"  
                              ContentTemplate="{TemplateBinding ContentTemplate}" 
                              Content="{TemplateBinding Content}" 
                              HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
                              Margin="{TemplateBinding Padding}" 
                              VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                              />
        </Border>

        <ControlTemplate.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Opacity" Value="0.8" />
            </Trigger>
        </ControlTemplate.Triggers>

    </ControlTemplate>
    <Style x:Key="StyleButtonTemplate" TargetType="{x:Type Button}">
        <Setter Property="Template" Value="{DynamicResource ButtonTemplate}" />
        <Setter Property="FontSize" Value="18pt" />
        <Setter Property="Foreground" Value="White" />
        <Setter Property="Cursor" Value="Hand" />
        <Setter Property="Button.Effect">
            <Setter.Value>
                <DropShadowEffect Color="Black" Direction="140" ShadowDepth="5" BlurRadius="5" Opacity="0.1" />
            </Setter.Value>
        </Setter>
    </Style>

【问题讨论】:

    标签: wpf mvvm controltemplate


    【解决方案1】:

    当您重新模板化控件时,所有视觉状态都应由您自己管理。在这种情况下,禁用状态将被忽略。如果IsEnabled 为假,则使用Trigger 更改背景的简单方法:

    <ControlTemplate.Triggers>
         <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Opacity" Value="0.8" />
         </Trigger>
         <Trigger Property="IsEnabled" Value="False">
            <Setter TargetName="border" Property="Background" Value="Gray"/>
         </Trigger>         
    </ControlTemplate.Triggers>
    

    【讨论】:

      猜你喜欢
      • 2012-12-30
      • 1970-01-01
      • 1970-01-01
      • 2016-10-13
      • 2016-07-12
      • 1970-01-01
      • 1970-01-01
      • 2019-04-07
      • 2013-04-25
      相关资源
      最近更新 更多