参考了园子里nasa写里的定时器的用法,以及旋转木马的部分代码,弄了一个小小的示例,贴在这里方便以后备查
目的:让某一个控件沿着圆形轨迹运动
xaml:采用Canvas布局,通过动态修改控件的Margin值来改变位置
cs代码:利用定时器触发来设置Margin值
xaml内容:
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">
cs代码:
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; }
}
}
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2298/viewspace-2801263/ ,如需转载,请注明出处,否则将追究法律责任。