我正在尝试为按钮创建一个模板,以防止控件在禁用时变灰,它工作得很好,但由于某种原因,一旦我为按钮属性设置颜色,它就不会改变背景.
这是我制作的按钮:
<Style TargetType="Button" x:Key="TestButton"> <Setter Property="SnapsToDevicePixels" Value="true" /> <Setter Property="OverridesDefaultStyle" Value="true" /> <Setter Property="MinHeight" Value="29px" /> <Setter Property="MinWidth" Value="103px" /> <Setter Property="Foreground" Value="Black" /> <Setter Property="Background" Value="#EEEEEE"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <Border TextBlock.Foreground="{TemplateBinding Foreground}" x:Name="Border"> <Border.Background> <SolidColorBrush Color="{TemplateBinding Background}" /> </Border.Background> <Border.BorderBrush> <SolidColorBrush Color="Black" /> </Border.BorderBrush> <Border.BorderThickness> <Thickness Top="0.75" Bottom="0.75" Right="0.75" Left="0.75"/> </Border.BorderThickness> <Border.CornerRadius> <CornerRadius TopLeft="3" TopRight="3" BottomLeft="3" BottomRight="3"/> </Border.CornerRadius> <ContentPresenter Margin="2" HorizontalAlignment="Center" VerticalAlignment="Center" RecognizesAccessKey="True" /> </Border> <!--Triggers--> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Background" Value="#E1F3FD" /> </Trigger> <Trigger Property="IsPressed" Value="True"> <Setter Property="Background" Value="#C4E9FF" /> <Setter Property="Effect"> <Setter.Value> <DropShadowEffect Color="Black" Direction="500" ShadowDepth="1" BlurRadius="5" Opacity="0.5" /> </Setter.Value> </Setter> </Trigger> <Trigger Property="IsEnabled" Value="false"> <Setter TargetName="Border" Property="Background" Value="{Binding RelativeSource={RelativeSource AncestorType=Button}, Path=Background}"/> <Setter Property="Opacity" Value="0.5" /> </Trigger> <Trigger Property="IsEnabled" Value="True" > <Setter TargetName="Border" Property="Background" Value="{Binding RelativeSource={RelativeSource AncestorType=Button}, Path=Background}" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style>
当我调用它时,它给了我两个不同的结果,一个有效的结果如下:
<Button Style="{DynamicResource ResourceKey=TestButton}" Content="Button" Height="66" Name="button1" Width="149" Click="button1_Click" />
但是当我向它添加背景时,由于某种原因它会停止更改背景:
<Button Style="{DynamicResource ResourceKey=TestButton}" Background="Orange" Content="Button" Height="66" Name="button1" Width="149" Click="button1_Click" />