发生在你身上的事情是正常的。创建按钮时,它将使用其默认属性,以防您不更改/覆盖它们。
在这种情况下,当您创建按钮时,您将覆盖Background
属性,但仅适用于按钮的正常状态。如果您希望在悬停时也改变背景,您应该告诉按钮这样做。
为此,我建议您使用样式覆盖按钮模板,如下所示:
<Window x:Class="ButtonTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ImageBrush x:Key="ButtonImage" ImageSource="/ButtonTest;component/Resources/ok.png"></ImageBrush>
<Style TargetType="Button">
<Setter Property="Background" Value="{StaticResource ButtonImage}"></Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" RecognizesAccessKey="True"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Foreground" Value="Blue" />
<Setter Property="Cursor" Value="Hand" />
<!-- If we don't tell the background to change on hover, it will remain the same -->
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="84,75,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
</Grid>
</Window>
在这种情况下,此样式将应用于您的所有按钮。您可以通过向您的样式添加一个x:Key
来指定要应用样式的按钮,然后在您的按钮中指定它:
<Style TargetType="Button" x:Key="ButtonStyled">
.....
<Button Style="{StaticResource ButtonStyled}" Content="Button" Height="23" HorizontalAlignment="Left" Margin="84,75,0,0" Name="button1" VerticalAlignment="Top" Width="75" />