在VisualState中更改值

时间:2014-09-24 08:16:03

标签: xaml windows-8 windows-store-apps win-universal-app

我使用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。

2 个答案:

答案 0 :(得分:2)

我最终创建了一个继承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自定义控件类中的依赖属性。 这有效,但我不知道这是否是最佳方法。

答案 1 :(得分:0)

这是一个非常好的问题。我会尝试定义附加的画笔属性并使用{TemplateBinding (myNamespace:PropertyClass.BrushPropertyName)},但我不确定它是否可行。什么工作是使用VisualTreeHelper在按钮的模板中找到VisualStateManager.VisualStateGroups(一旦加载),按名称查找组和状态,通过索引获取Storyboard / Animation / KeyFrame(从您无法阅读Storyboard目标的内容并设置Value。这有点hacky,但谁知道 - 也许它比解析另一个控件模板更快......另一个选择可能是尝试摆弄CustomVisualStateManager