WPF中button按鈕同時點(diǎn)擊多次觸發(fā)click解決方法
解決WPF中button按鈕同時點(diǎn)擊多次觸發(fā)click的方法,供大家參考,具體內(nèi)容如下
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; }
以上代碼并沒法解決用戶點(diǎn)擊兩次按鈕觸發(fā)兩次的問題,因?yàn)閡i線程是單線程的,所以這個這樣會導(dǎo)致用戶連續(xù)點(diǎn)擊兩次,會兩秒后又調(diào)用Button_Click一次,輸出如下:
1207.069,1;2017年4月19日 13:58:22
2055.1176,2;2017年4月19日 13:58:24
所以要在this.IsEnabled = false;后面強(qiáng)制界面刷新,代碼如下:
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();這個方法會強(qiáng)制界面刷新,問題就解決了。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Asp.net之TextBox只允許輸入數(shù)字的方法總結(jié)
Asp.net之TextBox只允許輸入數(shù)字的方法總結(jié),需要的朋友可以參考一下2013-02-02ASP.NET MVC使用jQuery Template實(shí)現(xiàn)批量更新
這篇文章介紹了ASP.NET MVC使用jQuery Template實(shí)現(xiàn)批量更新的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-07-07設(shè)置默認(rèn)Ajax操作cache and error
設(shè)置默認(rèn)Ajax操作cache and error,需要的朋友可以參考一下2013-02-02ASP.NET GridView的Bootstrap分頁樣式
這篇文章主要為大家詳細(xì)介紹了ASP.NET GridView的Bootstrap分頁樣式,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-11-11asp.net創(chuàng)建位圖生成驗(yàn)證圖片類(驗(yàn)證碼類)
本文提供一個asp.net生成驗(yàn)證圖片的類,功能是顯示簡單的字符串,大家參考使用吧2014-01-01asp.net Linq to Xml學(xué)習(xí)筆記
之前都沒有學(xué)習(xí)過關(guān)于XML文件的操作,由于最近開發(fā)的項(xiàng)目需要用到,開始時學(xué)習(xí)了原始的XML文件操作方法,看了半天,也看的頭暈眼花,沒學(xué)習(xí)到真正的用法,后來在同事的推薦下學(xué)習(xí)了Linq to Xml2010-03-03