【问题标题】:Change Value in VisualState更改 VisualState 中的值
【发布时间】:2014-09-24 08:16:03
【问题描述】:

我使用 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。这适用于使用通用 SDK 的 Windows 8.1 和 Windows Phone 8.1。

【问题讨论】:

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


    【解决方案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 自定义控件类中的一个依赖属性。 这可行,但我不知道这是否是最好的方法。

    【讨论】:

      【解决方案2】:

      这是一个很好的问题。我会尝试定义一个附加的画笔属性并使用{TemplateBinding (myNamespace:PropertyClass.BrushPropertyName)},但我不确定它是否会起作用。可行的是使用VisualTreeHelper 在按钮的模板中找到VisualStateManager.VisualStateGroups(一旦加载),按名称查找组和状态,按索引获取故事板/动画/关键帧(因为你不能阅读Storyboard 的目标)并设置Value。这有点 hacky,但谁知道呢 - 也许它会比解析另一个控件模板更快......另一个选择可能是尝试摆弄 CustomVisualStateManager

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-07-26
        • 2011-03-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-19
        • 2015-10-04
        相关资源
        最近更新 更多