WPF中button按钮同时点击多次触发click解决⽅法
iframe嵌套页面加载慢解决WPF中button按钮同时点击多次触发click的⽅法,供⼤家参考,具体内容如下
DateTime lastClick = DateTime.Now;
object obj = new object();
int i = 0;
private void Button_Click(object sender, RoutedEventArgs e)
{
this.IsEnabled = false;
var t = (DateTime.Now - lastClick).TotalMilliseconds;
i++;
lastClick = DateTime.Now;
System.Diagnostics.Debug.Print(t + "," + i + ";" + DateTime.Now);
Thread.Sleep(2000);
this.IsEnabled = true;
}
以上代码并没法解决⽤户点击两次按钮触发两次的问题,因为ui线程是单线程的,所以这个这样会导致⽤户连续点击两次,会两秒后⼜调⽤Button_Click⼀次,输出如下:
1207.069,1;2017年4⽉19⽇ 13:58:22 2055.1176,2;2017年4⽉19⽇ 13:58:24
所以要在this.IsEnabled = false;后⾯强制界⾯刷新,代码如下:
private void Button_Click(object sender, RoutedEventArgs e)
{
this.IsEnabled = false;
DispatcherHelper.DoEvents();
var t = (DateTime.Now - lastClick).TotalMilliseconds;
i++;
lastClick = DateTime.Now;
System.Diagnostics.Debug.Print(t + "," + i + ";" + DateTime.Now);
Thread.Sleep(2000);
this.IsEnabled = true;
}
public static class DispatcherHelper
{
[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public static void DoEvents()
{
DispatcherFrame frame = new DispatcherFrame();
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(ExitFrames), frame);
try { Dispatcher.PushFrame(frame); }
catch (InvalidOperationException) { }
}
private static object ExitFrames(object frame)
{
((DispatcherFrame)frame).Continue = false;
return null;
}
}
DispatcherHelper.DoEvents();这个⽅法会强制界⾯刷新,问题就解决了。
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论