您现在的位置是:网站首页> 编程资料编程资料
WPF中button按钮同时点击多次触发click解决方法_实用技巧_
2023-05-24
332人已围观
简介 WPF中button按钮同时点击多次触发click解决方法_实用技巧_
解决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();这个方法会强制界面刷新,问题就解决了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
您可能感兴趣的文章:
相关内容
- MVC页面之间参数传递解析_实用技巧_
- VS2015下OpenGL库配置教程_实用技巧_
- Visual Studio 2017安装失败的解决方法_实用技巧_
- VS2017添加EF的MVC控制器报错的解决方法_实用技巧_
- ASP.NET Core部署前期准备 使用Hyper-V安装Ubuntu Server 16.10_实用技巧_
- VS2017 Cordova Ionic2 移动开发环境搭建教程_实用技巧_
- ASP.NET MVC 4 中的JSON数据交互的方法_实用技巧_
- WPF下YUV播放的D3D解决方案_实用技巧_
- 解决WPF中空域问题(Airspace issuse)_实用技巧_
- WPF中在摄像头视频上叠加控件的解决方案_实用技巧_
