There are many different ways to implement double click in Silverlight, I chose to write it as a Trigger so it can be used anywhere and easily.
Of course you can write your own Action to use with that Trigger, but I wanted a most generic Action that will call a method and also could be used anywhere and easily.
The following Trigger (DoubleClick) & Action (InvokeMethodAction) classes act like any other event & handler. They can be used on any UIElement.
DoubleClick:
public class DoubleClick : TriggerBase<UIElement>
{
private readonly DispatcherTimer _timer;
private Point _clickPosition;
public DoubleClick()
{
_timer = new DispatcherTimer
{
Interval = new TimeSpan(0, 0, 0, 0, 300)
};
_timer.Tick += OnTimerTick;
}
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.MouseLeftButtonUp += new MouseButtonEventHandler(AssociatedObject_MouseLeftButtonUp);
}
void AssociatedObject_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
UIElement element = sender as UIElement;
if (_timer.IsEnabled)
{
_timer.Stop();
Point position = e.GetPosition(element);
if (Math.Abs(_clickPosition.X - position.X) < 1 && Math.Abs(_clickPosition.Y - position.Y) < 1)
{
InvokeActions(null);
}
}
else
{
_timer.Start();
_clickPosition = e.GetPosition(element);
}
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.MouseLeftButtonUp -= new MouseButtonEventHandler(AssociatedObject_MouseLeftButtonUp);
if (_timer.IsEnabled)
_timer.Stop();
}
private void OnTimerTick(object sender, EventArgs e)
{
_timer.Stop();
}
}
InvokeMethodAction:
public class InvokeMethodAction : TargetedTriggerAction<UIElement>
{
protected override void Invoke(object parameter)
{
if (MethodToInvoke != null)
{
MethodToInvoke(Target, null);
}
}
public delegate void Handler(object sender, RoutedEventArgs e);
public event Handler MethodToInvoke;
}
Download sample project here.