移动 canvas 内绘制的矩形

Move a rectangle drawn inside a canvas

我正在尝试移动 canvas 中绘制的矩形。当我 运行 我的代码时,我得到一个错误,基本上说 'Canvas.Top' 不受支持 属性。有任何想法吗?提前致谢。 这是我的代码:

<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>

您必须将 属性 括在括号中,因为这是附加的 属性:

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

看这里:Animating WPF element in XAML using attached property?