Many times, we want to disable the double click of a button in an application. This may be to avoid opening the same popup twice or to avoid saving a new record 2 times.
Whatever the reason, you may need to disable a specific button or, in my case, you may want to do this across the application by default.
To do it across the application in a clean way, include the following class in your project.
- public static class ControlHelper
- {
-
-
-
- public static readonly DependencyProperty DisableDoubleClickProperty =
- DependencyProperty.RegisterAttached("DisableDoubleClick", typeof(bool), typeof(ControlHelper), new FrameworkPropertyMetadata(false, OnDisableDoubleClickChanged));
-
-
-
-
-
-
- public static void SetDisableDoubleClick(UIElement element, bool value)
- {
- element.SetValue(DisableDoubleClickProperty, value);
- }
-
-
-
-
-
-
- public static bool GetDisableDoubleClick(UIElement element)
- {
- return (bool)element.GetValue(DisableDoubleClickProperty);
- }
-
-
-
-
-
-
- private static void OnDisableDoubleClickChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
- {
- var control = (Control)d;
- if ((bool)e.NewValue)
- {
- control.PreviewMouseDown += (sender, args) =>
- {
- if (args.ClickCount > 1)
- {
- args.Handled = true;
- }
- };
- }
- }
- }
Assuming, you have a common style defined for buttons in your application to maintain the same look and feel,
add the following line to the style applied to your buttons in the entire application.
- <Setter Property="helpers:ControlHelper.DisableDoubleClick" Value="true"/>
This should disable the double click of a button by default on all the buttons using that particular style.
To apply the same to a specific button, first add a namespace in which the ControlHelper class resides in the XAML page, using the following syntax.
- <Window xmlns:helpers="clr-namespace:MentionFulNameSpaceHere">
Then, use the following syntax to declare the button.
- <Button helpers:ControlHelper.DisableDoubleClick="true"/>
This should disable double click of a specifc button.