2009-10-28 63 views
1

我有一個標準的ButtonStyle應用於我的應用程序,該應用程序指定將文本內容從白色變爲黑色的鼠標懸停樣式。爲此,我嘗試修改按鈕模板,刪除ContentPresenter並用TextBlock替換它。然而,這意味着我不能有混合內容,如:帶有混合內容的WPF按鈕上的鼠標移過樣式

<Button 
    <Button.Content> 
     <StackPanel Orientation="Horizontal"> 
      <Path Margin="3" Width="12.375" Height="9.70833" Canvas.Left="0" Canvas.Top="0" 
        Stretch="Fill" Fill="#FF115485" 
        Data="F1 M 18.8333,7.08333L 16.7083,4.91667L 10.5,10.5417L 8.52083,8.6875L 6.45833,10.4792L 10.4792,14.625L 18.8333,7.08333 Z "/> 
      <TextBlock Margin="3">Hello</TextBlock> 
     </StackPanel> 
    </Button.Content> 
</Button> 

爲了改善這種情況,我然後把ContentPresenter回來,和我(純文本)按鈕指定ContentTemplate這樣的:

<Button IsDefault="True" Content="Text only Button" 
     ContentTemplate="{StaticResource TextButtonTemplate}" 
     Command="{Binding ...}" 
     CommandParameter="{...}" /> 

並與Template定義如下。此模板僅適用於帶有文本內容的Button,並根據混合內容的需要定義其他模板。

<DataTemplate x:Key="TextButtonTemplate"> 
    <TextBlock Text="{TemplateBinding Content}" 
       Foreground="{Binding Path=Foreground,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Button}}" /> 
</DataTemplate> 

有誰知道是否有一種方法,我可以通過保持所需的鼠標懸停風格進一步改善這一點,而無需定義自定義模板?

回答

1

假設內容沒有明確設定自己的任何顏色,你可以像這樣實現:

<Style x:Key="MyButtonStyle" TargetType="{x:Type Button}"> 
    <Style.Triggers> 
     <Trigger Property="IsMouseOver" Value="True"> 
      <Setter Property="TextBlock.Foreground" Value="Red" /> 
     </Trigger> 
    </Style.Triggers> 
</Style> 

這工作,因爲TextBlock.Foreground是一種遺傳特性。只要Button內容中的控件沒有明確地設置它們自己的前景,就可以工作。如果他們設置了自己的顏色,所有投注都將關閉。

+0

謝謝你的回答。我以前沒有做過任何與遺傳屬性有關的事情。不幸的是,我的TextBlocks確實設置了自己的顏色,因爲我不希望它們使用系統默認值。我可能需要在該問題上發佈一個新問題..... – 2009-11-04 00:22:00

+0

不適合我。 – flq 2012-07-27 10:46:07