Search code examples
wpfxamlanimationmoverect

Move a rectangle drawn inside a canvas


I am trying to move a rectangle drawn inside a canvas. When I run my code I get an error which basically says 'Canvas.Top' is not a supported property. Any ideas? Thanks in advance. Here is my code:

<Window.Resources>
    <ResourceDictionary>
        <Storyboard x:Key="MoveRect">
            <DoubleAnimation Storyboard.TargetName="box" Storyboard.TargetProperty="Canvas.Top" 
                             From="0" To="100" Duration="0:0:1"/>
        </Storyboard>
    </ResourceDictionary>
</Window.Resources>

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>

    <Canvas Grid.Row="0" Width="200" Height="200" HorizontalAlignment="Left">
        <Rectangle x:Name="box" Width="100" Height="100" Fill="LightBlue" Stroke="DarkBlue" StrokeThickness="3" 
                   Canvas.Top="0" Canvas.Left="0"/> 
    </Canvas>

    <Button Grid.Row="1" Content="Move" Width="100" HorizontalAlignment="Left" Click="Button_Click"/>
</Grid>

Solution

  • You have to enclose the property in parentheses, because that's an attached property:

            <DoubleAnimation 
                Storyboard.TargetName="box"
                Storyboard.TargetProperty="(Canvas.Top)" 
                From="0"
                To="100"
                Duration="0:0:1"
                />
    

    Have a look here: Animating WPF element in XAML using attached property?