参考了园子里nasa写里的定时器的用法,以及旋转木马的部分代码,弄了一个小小的示例,贴在这里方便以后备查
目的:让某一个控件沿着圆形轨迹运动
xaml:采用Canvas布局,通过动态修改控件的Margin值来改变位置
cs代码:利用定时器触发来设置Margin值
xaml内容:
Code
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SilverlightApplication2.Page"
Width="300" Height="300" xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">
<Canvas x:Name="LayoutRoot" Background="White">
<TextBlock x:Name="txtTime" Height="10" Width="10" Text="A" Canvas.Left="10" Canvas.Top="10" FontSize="12" Foreground="Red" />
<Ellipse Height="200" Width="200" Canvas.Left="10" Canvas.Top="10" Fill="{x:Null}" Stroke="#22000000" Canvas.ZIndex="-1"/>
</Canvas>
</UserControl>
cs代码:
Code
using System;
using System.Windows.Controls;
using System.Windows.Threading;
namespace SilverlightApplication2
{
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
DispatcherTimer dt = new DispatcherTimer();
dt.Interval = new TimeSpan(0, 0, 0, 0, 100); // 50 Milliseconds
dt.Tick += new EventHandler(dt_Tick);
dt.Start();
}
int angle = 0;
int radius = 100;
void dt_Tick(object sender, EventArgs e)
{
angle = angle + 1;
txtTime.Text = new System.Random().Next(1, 10).ToString();
//Margin.Left = 半径*sin(角度),Margin.Top = 半径*cos(角度)--注意:角度要换成弧度,同时加上平移量
txtTime.Margin = new System.Windows.Thickness(radius * Math.Cos(angle * Math.PI / 180) + radius, radius * Math.Sin(angle * Math.PI / 180) + radius, 0, 0);
if (angle > 360) { angle = 0; }
}
}
}