2012-12-13 65 views
1

我是一个初学者,试图了解WPF和XAML是如何工作的。下面的片段是来自Nathans Unleashed 4.0书籍(一个微不足道的修改)。我插入它变成一个OK按钮:IsMouseOver仅触发背景颜色变化

<Button.Style> 
<Style TargetType=”{x:Type Button}”> 
    <Style.Triggers> 
    <Trigger Property=”IsMouseOver” Value=”True”> 
    <Setter Property=”Background” Value=”Yellow”/> 
    </Trigger> 
    </Style.Triggers> 
</Style> 
</Button.Style> 

当我运行这在XAML crunsher和将鼠标移动到OK按钮,该按钮不会改变它的背景色为黄色(细),但立即复位颜色它是原始值,即使鼠标停留在按钮上 - 为什么是这样?我希望它保持黄色,直到鼠标离开按钮。这是XAML crunsher的问题,还是我的期望错误?

编辑(回应评论):这里是完整的窗口,这是从内森的书取,太:

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="About WPF Unleashed" SizeToContent="WidthAndHeight" 
    Background="OrangeRed"> 
    <StackPanel> 
    <Label FontWeight="Bold" FontSize="20" Foreground="White"> 
    WPF Unleashed (Version 3.0) 
    </Label> 
    <Label>© 2006 SAMS Publishing</Label> 
    <Label>Installed Chapters:</Label> 
    <ListBox> 
    <ListBoxItem>Chapter 1</ListBoxItem> 
    <ListBoxItem>Chapter 2</ListBoxItem> 
    </ListBox> 
    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center"> 
    <Button MinWidth="75" Margin="10">Help</Button> 
    <Button MinWidth="75" Margin="10"> 
    <Button.Style> 
    <Style TargetType="{x:Type Button}"> 
     <Style.Triggers> 
     <Trigger Property="IsMouseOver" Value="True"> 
     <Setter Property="Background" Value="Yellow"/> 
     </Trigger> 
     </Style.Triggers> 
    </Style> 
    </Button.Style> 
    OK 
    </Button> 
    </StackPanel> 
    <StatusBar>You have successfully registered this product.</StatusBar> 
    </StackPanel> 
</Window> 
+3

您的期望是完全正确的,我复制了您的代码,它的工作方式与您的预期一致。 –

+0

您是否使用按钮的自定义模板? –

+0

@ErikÖjebo不,据我所知,这只是一个普通的按钮。更糟糕的是,如果我使用“前景”而不是“背景”,它会按预期工作(即,前景色保持不变,直到鼠标离开按钮)。 – Thomas

回答

1

不幸的是,动画上的花式悬停是嵌入到按钮中的,您将不得不重写ControlTemplate来阻止这种情况发生。

<Button MinWidth="75" Margin="10" FocusVisualStyle="{x:Null}" Content="OK"> 
      <Button.Style> 
       <Style TargetType="{x:Type Button}"> 
        <Setter Property="Template"> 
         <Setter.Value> 
          <ControlTemplate TargetType="{x:Type Button}"> 
           <Border Name="border" BorderThickness="1" Padding="4,2" BorderBrush="DarkGray" CornerRadius="3" Background="{TemplateBinding Background}"> 
            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" Name="content"/> 
           </Border> 
          </ControlTemplate> 
         </Setter.Value> 
        </Setter> 
        <Style.Triggers> 
         <Trigger Property="IsMouseOver" Value="True"> 
          <Setter Property="Background" Value="Yellow"/> 
         </Trigger> 
        </Style.Triggers> 
       </Style> 
      </Button.Style> 
     </Button> 
0

我复制你的代码到一个新的Visual Studio 2010项目并运行它成功(.NET 4.0)。

我相信这个问题是XAML Cruncher的一个错误。