我使用 ControlTemplate 为按钮创建不同的样式。当然,它的目标是 Button 类型。我可以更改不同 VisualStates 的按钮颜色,但它们都是硬类型的或者引用静态资源。
示例:
<VisualState x:Name="Pressed">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter"
Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="Blue" />
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
在页面上我放置了一个按钮:
<Button Template="{StaticResource ResourceKey=ButtonDefaultStyle}"
Background="Yellow"
Content="Hello" />
该按钮是黄色的,当您按下它时,它会变成蓝色。
现在的问题是,如何更改 VisualState::Pressed 的颜色?对我来说,为每个不同颜色的按钮创建 ControlTemplate 很麻烦。
我正在使用 Visual Studio 2013 Express Update 3。这适用于使用 Universal SDK 的 Windows 8.1 和 Windows Phone 8.1。
最佳答案
我最终创建了一个继承 Button 的自定义控件。在该类中,我创建了一堆依赖属性,允许我为每个状态设置不同的颜色。
按钮的资源字典如下所示:
<VisualState x:Name="Pressed">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="Border">
<DiscreteObjectKeyFrame KeyTime="0" Value="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=PressedColor}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
页面本身的按钮如下所示:
<cc:ButtonStandard Style="{StaticResource ButtonStandardStyle}"
Content="Hello Visual Studio"
Background="Red"
PointerOverColor="Blue"
PressedColor="Orange"
DisabledColor="White"/>
PressedColor 是 ButtonStandard 自定义控件类内的依赖属性。 这可行,但我不知道这是否是最好的方法。
关于xaml - 更改 VisualState 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26011888/