This article is mainly for you in detail in the WPF button buttons simultaneously click on multiple triggering the click of the solution, with a certain reference value, interested in small partners can refer to
To solve the WPF button buttons at the same time click to trigger the click of the method, for your reference, the specific content is as follows
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 (+); This. IsEnabled = true; }
The above code does not solve the user click two times the button triggered two times the problem, because the UI thread is single-threaded, so this will cause the user to click two consecutive times, two seconds and then call Button_Click once, the output is as follows:
1207.069,1;2017 April 19 13:58:22
2055.1176,2;2017 April 19 13:58:24
So to be in this. IsEnabled = false; After forcing the interface to refresh, the code is as follows:
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 (+); 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 (); This method forces the interface to refresh, and the problem is resolved.