Search code examples
silverlight-4.0visualstatemanager

VisualStateManager.GoToState always returning false


This one's stumped me. So I have the following sample app that is supposed to animate the opacity of a border element when the mouse is hovered over it. `

<UserControl.Resources>
    <Style x:Key="borderstyle" TargetType="ContentControl">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ContentControl">
                    <Grid>

                        <VisualStateManager.VisualStateGroups>

                            <VisualStateGroup>
                                <VisualState x:Name="FirstState">
                                    <Storyboard>
                                        <DoubleAnimation To="1.0" Storyboard.TargetName="border" Storyboard.TargetProperty="Opacity" FillBehavior="HoldEnd"/>
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>

                        </VisualStateManager.VisualStateGroups>

                        <Border Background="Blue" x:Name="border" Opacity="0.0"/>

                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>

    </Style>
</UserControl.Resources>


<Grid x:Name="LayoutRoot" Background="White">
    <Border BorderBrush="Red" BorderThickness="1" Width="51" Height="51">
        <ContentControl Width="50" Height="50" Style="{StaticResource borderstyle}"  MouseEnter="OnMouseEntered" />
    </Border>
</Grid>

`

And in code behind I have the following code...

    private void OnMouseEntered(object sender, MouseEventArgs e)
    {
        bool status = VisualStateManager.GoToState(this, "FirstState", true);
    }

And...nothing happens. status is always false and the animation never fires.

I'm not sure whats missing here.


Solution

  • You should specify your ContentControl as the control which state is changing:

    private void OnMouseEntered(object sender, MouseEventArgs e)
    {
        bool status = VisualStateManager.GoToState((ContentControl)sender, "FirstState", false);
    }