blog.troelsrichter.dk
alt mellem bits og bytes

How to add MouseDoubleClick events to Silverlight 4

Tuesday, 9 November 2010 22:18 by dommer

In Silverlight 4 there is no support for mouse double click events. The best work around from my point of view is to implement a double click behavior that exposes a double click event.

This is how the Xaml will look like if you want something to happen when a user double clicks on a grid:


<Grid>
  <Interactivity:Interaction.Behaviors>
    <MouseDoubleClickBehavior MouseDoubleClick="Grid_MouseDoubleClick" />
  </Interactivity:Interaction.Behaviors>
</Grid>

It is by far a beautiful programmer experience but I think it is the best solution as it is right now.

The source code behind the MouseDoubleClickBehavior can be found below:

 public class MouseDoubleClickBehavior : Behavior<FrameworkElement>

    {
        public event EventHandler<EventArgs> MouseDoubleClick;
        private readonly DispatcherTimer timer;

        public MouseDoubleClickBehavior()
        {
            timer = new DispatcherTimer() {Interval = new TimeSpan(0, 0, 0, 0, 200) };
            timer.Tick += timer_Tick;
        }

        void timer_Tick(object sender, EventArgs e)
        {
            timer.Stop();
        }

        protected override void OnAttached()
        {
            base.OnAttached();
            this.AssociatedObject.MouseLeftButtonDown += AssociatedObject_MouseLeftButtonDown;
        }

        void AssociatedObject_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (timer.IsEnabled)
            {
                OnMouseDoubleClick();
            } else
            {
                timer.Start();
            } 
        }

        virtual protected void OnMouseDoubleClick()
        {
            if (MouseDoubleClick != null)
            {
                MouseDoubleClick(this, new EventArgs());
            }
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            this.AssociatedObject.MouseLeftButtonDown -= AssociatedObject_MouseLeftButtonDown;
            timer.Stop();
        }
    }

 

If you use this remember to add a reference to System.Windows.Interactivity.dll which can be found in the Expression Blend SDK

Tags:   ,
Categories:  
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed