使用VisualStateManager按下时更改按钮的背景图像

时间:2011-01-17 10:07:27

标签: silverlight xaml windows-phone-7

我有这个按钮:

<Button x:Name="PrevAdIcon" Tag="-1" Visibility="Collapsed" Width="80" Height="80" Click="PrevAd">
    <Button.Background>
        <ImageBrush AlignmentY="Top" Stretch="None" ImageSource="/Images/prev.png"></ImageBrush>
    </Button.Background>
</Button>

当用户按下按钮时,如何将背景更改为/Images/prev-selected.png?它会给他一个反馈,因为它是一个WP7应用程序

到目前为止(不工作):

<vsm:VisualState x:Name="Pressed">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames BeginTime="00:00:00"  Duration="00:00:00.0010000" Storyboard.TargetName="Background" Storyboard.TargetProperty="Background">
                                            <DiscreteObjectKeyFrame KeyTime="0">
                                                <DiscreteObjectKeyFrame.Value>
                                                    <ImageBrush ImageSource="/Images/prev-selected.png" Stretch="Fill"/>
                                                </DiscreteObjectKeyFrame.Value>
                                            </DiscreteObjectKeyFrame>
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </vsm:VisualState>

3 个答案:

答案 0 :(得分:5)

据我所知,您无法使用VisualStateManager更改Image元素的Source属性的值。但是,您只需向ControlTemplate添加两个Image元素:一个用于Normal状态,另一个用于Pressed状态,并在Pressed状态下切换Visibility。


<VisualState x:Name="Pressed">
    <Storyboard>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="Img">
            <DiscreteObjectKeyFrame KeyTime="0" Value="Collapsed" />
        </ObjectAnimationUsingKeyFrames>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="PressedImg">
            <DiscreteObjectKeyFrame KeyTime="0" Value="Visible" />
        </ObjectAnimationUsingKeyFrames>
    </Storyboard>
</VisualState>

答案 1 :(得分:4)

有关如何执行此操作的示例和解释,请参阅Peter Torr关于“Why can't I change the Background of my Button on a Click event?”的帖子。

答案 2 :(得分:3)

要向Derek的答案添加更多信息,您应该查看Gambit的答案here,了解有效的完整XAML