2012-12-13 68 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的一個錯誤。