How to move a Silverlight Rectangle?
I want to say rect1.X++ to move a rectangle as a timer event is activated... It's easy to change the height like rect1.Height+开发者_开发百科+;
Is there some easy way to do this without having to deal with complex matrices?
You need to use a TranslateTransform to move an element:
<Rectangle Width="50" Height="50" HorizontalAlignment="Left" VerticalAlignment="Top" Fill="Red">
<Rectangle.RenderTransform>
<TranslateTransform x:Name="myTranslateTransform" />
</Rectangle.RenderTransform>
</Rectangle>
You can then reference it in code:
myTranslateTransform.X = 30;
myTranslateTransform.Y = 100;
However, the "correct" way (and also the way you can do other things like animate the translation) would be to set the values for the transform in the VisualStateManager and use VisualStateManager.GoToState()
instead of manipulating the values in code directly like above.
If it's on a canvas, set the Canvas.LeftProperty
and Canvas.TopProperty
values. Here's a snip from one of my projects, moving a (rectangular) foot:
// at startup:
_rightFoot = new Rectangle();
_myCanvas.Children.Add(_rightFoot);
// during animation cycle:
_rightFoot.SetValue(Canvas.LeftProperty, _xRight - _footWidth/2);
_rightFoot.SetValue(Canvas.TopProperty, _yRight - _footHeight/2);
精彩评论