We had to perform some business logic when a user double click’s on a Image, unfortunately till the current version of silverilght( version 4.x) there is no double click event. In future versions of silverlight we might get the double click functionality but for right now we will have to get this done by our self. So how do we implement double click event? The trick is to start a timer and check if the MouseLeftButtonDown event is fired again in certain duration(milliseconds).
Code is very simple and short, In the xaml we have a Image with a MouseLeftButtonDown event in the code behind we add a dispatch timer which is a part of System.Windows.Threading. On the first click start the timer, when next click event is fired check if the timer is active, if the timer is active then it is a double click so go ahead and perform the intended action.
- private DispatcherTimer timer;
- public MainPage()
- {
- InitializeComponent();
- timer = new DispatcherTimer();
- timer.Interval = new TimeSpan(0, 0, 0, 200);
- timer.Tick += new EventHandler(( sender, e) => { timer.Stop(); });
- }
- private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
- {
- if (!timer.IsEnabled)
- {
- timer.Start();return;
- }
- timer.Stop();
- HandleDoubleClick();
- }
DoubleClick Class
The above functionality can be encapsulated in a class for a cleaner looking code. The class ‘DoubleClick’ has a dispatch timer and a public event. In the constructor you pass the UIElement as parameter and hook the MouseLeftButtonDown event. The timer tick event has an inline event handler defined that will stop the timer on the first tick.
- namespace DoubleClickInSL4
- {
- using System.Windows.Threading;
- public class DoubleClick
- {
- private const int dblclickDelay = 200;
- private DispatcherTimer timer;
- public event MouseButtonEventHandler MouseDoubleClick;
- public DoubleClick(UIElement uiElement)
- {
- timer = new DispatcherTimer();
- timer.Interval = new TimeSpan(0, 0, 0, dblclickDelay);
- timer.Tick += new EventHandler((sender, e) => { timer.Stop(); });
- uiElement.MouseLeftButtonDown += new MouseButtonEventHandler(UIElement_MouseLeftButtonDown);
- }
- private void UIElement_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
- {
- if (!timer.IsEnabled)
- {
- timer.Start();
- return;
- }
- timer.Stop();
- //HandleDoubleClick();
- if (MouseDoubleClick != null)
- {
- MouseDoubleClick(sender, e);
- }
- }
- }
- }
Rx Framework
A very interesting use of the Rx framework can simplify the above code to just couple of lines. In the MouseLeftButtonDown event we add a Observable.FromEvent and set TimeInterval, so when the event is fired for the first time the timer starts. On the second event the code in the body of lambda will be executed which checks if duration is greater then 300.
- private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
- {
- Observable.FromEvent<MouseButtonEventArgs>(this.LayoutRoot, "MouseLeftButtonDown").TimeInterval().Subscribe(evt =>
- {
- if (evt.Interval.Milliseconds >= 300)
- {
- // Do something on double click
- }
- });
- }
Doubleclick Behaviour
The above code is helpful for application that handles the logic directly in the codebehind, so how about MVVM application where the application logic is handled in the model view. A decent solution for such a scenario would be to write a behavior that implements the double click functionality. There are many posts which explain how to create a behaviors so I will not go in details, basically this double click behavior have a dependency property named as DoubleClickCommand that will bind to a property in the view model of type ICommand. I created a class called as DelegateCommand which implements the interface ICommand, this class will be instantiated in the view model and assigned to view models property.
- namespace DoubleClickInSL4
- {
- using System.Windows.Threading;
- public class DoubleClickBehavior : Behavior<UIElement>
- {
- private const int dblclickDelay = 200;
- private DispatcherTimer timer;
- public object CommandParameter
- {
- get { return (object)GetValue(CommandParameterProperty); }
- set { SetValue(CommandParameterProperty, value); }
- }
- public ICommand DoubleClickCommand
- {
- get { return (ICommand)GetValue(DoubleClickCommandProperty); }
- set { SetValue(DoubleClickCommandProperty, value); }
- }
- public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register
- ("CommandParameter", typeof(object), typeof(DoubleClickBehavior), new PropertyMetadata(CommandParameterChanged));
- private static void CommandParameterChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { }
- public static readonly DependencyProperty DoubleClickCommandProperty = DependencyProperty.Register
- ("DoubleClickCommand", typeof(ICommand), typeof(DoubleClickBehavior), new PropertyMetadata(DoubleClickCommandChanged));
- private static void DoubleClickCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { }
- public DoubleClickBehavior()
- {
- timer = new DispatcherTimer();
- timer.Interval = new TimeSpan(0,0, 0, 0, dblclickDelay);
- timer.Tick += new EventHandler((sender, e) =>
- { timer.Stop(); });
- }
- protected override void OnAttached()
- {
- base.OnAttached();
- AssociatedObject.MouseLeftButtonDown += UIElement_MouseLeftButtonDown;
- }
- protected override void OnDetaching()
- {
- base.OnDetaching();
- AssociatedObject.MouseLeftButtonDown -= UIElement_MouseLeftButtonDown;
- }
- private void UIElement_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
- {
- if (!timer.IsEnabled)
- {
- timer.Start();
- return;
- }
- timer.Stop();
- //HandleDoubleClick();
- if (CommandParameter != null)
- DoubleClickCommand.Execute(CommandParameter);
- }
- }
- }
- namespace DoubleClickInSL4
- {
- public class DelegateCommand : ICommand
- {
- Func<object, bool> canExecute;
- Action<object> executeAction;
- bool canExecuteCache;
- public DelegateCommand(Action<object> executeAction, Func<object, bool> canExecute)
- {
- this.executeAction = executeAction;
- this.canExecute = canExecute;
- }
- #region ICommand Members
- public bool CanExecute(object parameter)
- {
- bool temp = canExecute(parameter);
- if (canExecuteCache != temp)
- {
- canExecuteCache = temp;
- if (CanExecuteChanged != null)
- {
- CanExecuteChanged(this, new EventArgs());
- }
- }
- return canExecuteCache;
- }
- public event EventHandler CanExecuteChanged;
- public void Execute(object parameter)
- {
- executeAction(parameter);
- }
- #endregion
- }
- }
Here is the code for the MainPage.xaml.cs
- using System;
- using System.Collections.Generic;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Documents;
- using System.Windows.Input;
- using System.Windows.Threading;
- using System.Windows.Interactivity;
- namespace DoubleClickInSL4
- {
- public class myViewModel
- {
- public ICommand DoubleCommand { get; set; }
- public myViewModel()
- {
- DoubleCommand = new DelegateCommand(myAction, canExe);
- }
- private void myAction(object param)
- { //Write your action here }
- private bool canExe(object param)
- { return true; }
- }
- public partial class MainPage : UserControl
- {
- public MainPage()
- {
- InitializeComponent();
- Image.DataContext = new myViewModel();
- }
- }
- }
Here is the xaml for the MainPage.xaml.
- <UserControl x:Class="DoubleClickInSL4.MainPage"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
- xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
- xmlns:Local="clr-namespace:DoubleClickInSL4"
- mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400">
- <UserControl.Resources>
- <Local:myViewModel x:Name="vm"/>
- </UserControl.Resources>
- <Grid x:Name="LayoutRoot" Background="White" Height="300" Width="400">
- <Image x:Name="Image" Source="Images/80_20.jpg" >
- <i:Interaction.Behaviors>
- <Local:DoubleClickBehavior DoubleClickCommand="{Binding DoubleCommand}" CommandParameter="{Binding ElementName=Image,Path=Source}"/>
- </i:Interaction.Behaviors>
- </Image>
- </Grid>
- </UserControl>
Extending Silverlight mouse events
SharpGIS has a very interesting blog post about extending the silverlight mouse events. Including double-clicks they have provided many more extensions with source code and a online demo.
http://www.sharpgis.net/post/2009/05/02/Extending-Silverlighte28099s-mouse-events.aspx