How can I move an object left and right with silverlight?
I currently have two buttons that s开发者_运维技巧ay left and right, and I want them to move a square object left and right respectively.
What its currently doing when i press left is moving the square to the left, and if I press left again, it resets from the center and goes left.
I want it so that when I press left, from where ever it is currently to go left and right.
I know the principle is something like get current objects position and add the canvas coordinates respectively but how do I do this?
<UserControl x:Class="phase_2.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<UserControl.Resources>
<Storyboard x:Name="scroll_me">
<DoubleAnimation x:Name="left_ani" To="0" Duration="0:0:01" Storyboard.TargetName="Rect_Animate" Storyboard.TargetProperty="(Canvas.Left)">
<DoubleAnimation.EasingFunction>
<PowerEase EasingMode="EaseOut"></PowerEase>
</DoubleAnimation.EasingFunction>
</DoubleAnimation>
</Storyboard>
<Storyboard x:Name="scroll_me2">
<DoubleAnimation x:Name="right_ani" To="200" Duration="0:0:01" Storyboard.TargetName="Rect_Animate" Storyboard.TargetProperty="(Canvas.Left)">
<DoubleAnimation.EasingFunction>
<PowerEase EasingMode="EaseOut"></PowerEase>
</DoubleAnimation.EasingFunction>
</DoubleAnimation>
</Storyboard>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="2*"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="1*"/>
<RowDefinition Height="35"/>
<RowDefinition Height="1*"/>
</Grid.RowDefinitions>
<Canvas Grid.Column="1" Grid.Row="1" x:Name="canvas1">
<Rectangle x:Name="Rect_Animate" Width="35" Height="35" Fill="Red" Canvas.Left="80" />
</Canvas>
<Button x:Name="left_btn" Width="35" Height="35" Content="L" Grid.Column="0" Grid.Row="1" Click="left_btn_Click"/>
<Button x:Name="right_btn" Width="35" Height="35" Content="R" Grid.Column="2" Grid.Row="1" Click="right_btn_Click"/>
</Grid>
Only if your object is contained in a Canvas, which in general is not a great layout practice - it isn't flexible.
If you're placing items in a Grid instead, you can do exactly what the designer tools like Blend do: adjust the Margin of any item you want to move. You can have negative margins.
精彩评论