WPF中实现单双击,单双击互斥
在XAML界面设计器中添加MouseLeftButtonDown事件,或MouseDown事件
以下为代码部分:
#region 左击事件(分单双击)
int i = 0;
bool 有双击 = false;
private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) //MouseLeftButtonDown事件
{
i += 1;
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0, 0, 0, 0, 200);
timer.Tick += (s, e1) => { timer.IsEnabled = false; i = 0; 单击(); 有双击 = false; };
timer.IsEnabled = true;
if (i % 2 == 0)
{
timer.IsEnabled = false;
i = 0;
有双击 = true;
//双击时执行的代码
//MessageBox.Show("DoubleClick!");
}
}
private void 单击()
{
if (!有双击)
{
//单击时执行的代码
}
}
#endregion
第二种办法(看别人的)
private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) //MouseLeftButtonDown事件
{
var element = (FrameworkElement)sender;
if (e.ClickCount == 1)
{
var mytimer = new System.Timers.Timer(300);
mytimer.AutoReset = false;
mytimer.Elapsed += new ElapsedEventHandler((o, ex) => element.Dispatcher.Invoke(new Action(() =>
{
var timer2 = (System.Timers.Timer)element.Tag;
timer2.Stop();
timer2.Dispose();
//左单击();
})));
mytimer.Start();
element.Tag = mytimer;
}
if (e.ClickCount > 1)
{
var mytimer = element.Tag as System.Timers.Timer;
if (mytimer != null)
{
mytimer.Stop();
mytimer.Dispose();
//左双击();
}
}