WPF中实现winform的Timer控件效果的类--DispatcherTimer
今天在捣鼓WPF程序的时候,想实现移动悬浮控件的效果,半天没找到熟悉的Timer控件,在MSDN上逛了一圈才发现可以使用DispatcherTimer类
来实现Timer控件的功能。下面是自己写的实现移动的主要代码,供像我一样的初学者参考:
public partial class AllDocInWF : UserControl
{
//用以设置DockPanel的移动
private DispatcherTimer dpTimer;
public AllDocInWF()
{
InitializeComponent();
dpTimer = new DispatcherTimer();
dpTimer.Tick += new EventHandler(dpTimer_Tick);
dpTimer.Interval = TimeSpan.FromSeconds(0.1);
}
//设置所执行的操作
private void dpTimer_Tick(object sender, EventArgs e)
{
Point point = Mouse.GetPosition(this);
Canvas.SetLeft(this.dpApprove, point.X);
Canvas.SetTop(this.dpApprove, point.Y);
}
//鼠标左键弹起停止Timer
private void UserControl_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
this.dpTimer.Stop();
}
//鼠标左键按下启动Timer
private void dpApprove_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
this.dpTimer.Start();
}
}