你可以做你在尋找什麼,而不必使用ContentControl
並通過只使用VisualStateManager
我當然可以通過編輯樣式更改文本顏色,但這不是有用它在我感興趣的編輯狀態之內。
因此,例如說,國家對新Foreground
顏色應用到你的Button
是MouseOver
文字,
- 首先混合物不爲
Button.MouseOver.Foreground
編輯Button
模板時創建Brush
資源。
所以我們來創建一個。(只需添加以下行與其他刷資源一起)
<SolidColorBrush x:Key="Button.MouseOver.Foreground" Color="Tomato" />
- 現在我們可以應用
Storyboard
到contentPresenter
的TextElement.Foreground
。
所以你的VSM將類似於:
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="MouseOver">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="contentPresenter"
Storyboard.TargetProperty="(TextElement.Foreground)">
<DiscreteObjectKeyFrame KeyTime="0">
<DiscreteObjectKeyFrame.Value>
<SolidColorBrush Color="{Binding Source={StaticResource Button.MouseOver.Foreground}, Path=Color}" />
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="Pressed"/>
<VisualState x:Name="Disabled"/>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
,就是這樣。
請注意,我們在這裏做什麼就可以了僅當Button
的Content
僅僅是文字,但因爲這是您的使用是什麼在你的問題中提到,你應該罰款。
旁註:
您可以通過只切換ContentPresenter
到TextBlock
在ControlTemplate
做同樣的事情。
如果您需要Foreground
可用的Button
任何Content
,然後葉剛剛切換ContentPresenter
到ContentControl
,你仍然可以在故事板VSM在一個非常類似的方式。
更新:
要切換ContentPresenter
到ContentControl
,在你ControlTemplate
只需切換實際元素與新的。
<ControlTemplate TargetType="{x:Type Button}">
...
<ContentPresenter x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" RecognizesAccessKey="True"/>
...
</ControlTemplate>
到:
<ControlTemplate TargetType="{x:Type Button}">
...
<ContentControl x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Content="{TemplateBinding Content}"/>
...
</ControlTemplate>
,你將不得不更新自己相應的屬性像如ContentControl
不支持RecognizesAccessKeys
,它也需要它Content="{TemplateBinding Content}"
設置爲實際顯示的內容。使用ContentPresenter
Content
屬性是隱式設置的。
來源
2013-07-09 10:47:32
Viv
我不明白你爲什麼不能在風格上做到這一點。 –
嗨Viktor,非常感謝您的回答,但是我想盡可能避免觸發器,因爲我正在尋找更靈活的東西(即設置它並忘記它),因爲我對文本屬性做了很多工作,每次都想設置觸發器。 Viv的回答是我遵循的,更新部分,因爲這允許我使用文本,就好像它只是一個普通的文本框。非常感謝您的幫助,雖然 –