sliverlight簡單方法實現雙擊觸發

張國平發表於2010-03-14

sliverlight本身沒有提供DoubleClick,如果實現可以在網上找到很多實現發方法,

我試了幾個,這邊這個算是最簡單的,不過對於button這種已經繫結了click觸發器總是有問題,

對於其他所有控制元件都可以正常使用,只要繫結了MouseLeftButtonDown和MouseLeftButtonUp這兩個觸發器就OK了

實現原理很簡單,記錄MouseLeftButtonUp和MouseLeftButtonDown的時間戳,計算時間差,只要小於1/10秒就可以,大於0就算雙擊,就是雙擊中第一次點選和第二次點選時間差小於1/10秒。

實現程式碼:

    public class GraphicsUtils
    {
        #region Double click

        ///


        /// Holds the millis for the first click.
        ///

        private long lastClickedTime = 0;

        ///


        /// Delegate definition for the call back function.
        ///

        ///
        ///
        public delegate void DoubleClickHandler(object sender, MouseButtonEventArgs e);

        ///


        /// Holder for the call back function.
        ///

        private DoubleClickHandler doubleClickCallBackFunction;
        ///
        /// This will attach a double click to an object.
        ///

        ///
        /// Due to Silverlight lack of double click event a custom implementation is needed.
        /// this function and its adjacent handlers will attach a double click event to any object
        /// deriving from UIElement.
        ///

        /// the UIElement to attach the event to.
        /// the function to call upon the double click event.
        public void AttachDoubleClick(object doubleClickTarget, DoubleClickHandler function)
        {
            UIElement target = (UIElement)doubleClickTarget;
            target.MouseLeftButtonUp += new MouseButtonEventHandler(target_MouseLeftButtonUp);
            target.MouseLeftButtonDown += new MouseButtonEventHandler(target_MouseLeftButtonDown);
            doubleClickCallBackFunction = function;
        }

        private void target_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            lastClickedTime = DateTime.Now.Ticks / 10000;
        }

        private void target_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            long currentMillis = DateTime.Now.Ticks / 10000;

            if (currentMillis - lastClickedTime < 100 && currentMillis - lastClickedTime > 0)
            {
                //HERE IS DOUBLE CLICK
                doubleClickCallBackFunction(sender, e);
            }

        }

        #endregion
    }

使用方法,比如裡面有個橢圓,名稱是doubleclick,那麼繫結方法如下:

    GraphicsUtils.DoubleClickHandler dblClickHandler = new GraphicsUtils.DoubleClickHandler(MyMethodToHandleDoubleClick);
            GraphicsUtils gu = new GraphicsUtils();
            gu.AttachDoubleClick(this.doubleclick, dblClickHandler);

MyMethodToHandleDoubleClick是雙擊觸發的事件,很簡單,就和click事件一樣寫、

這個可以放在頁面初始化時候進行繫結,是一個比較方便簡單的方法,

原載與

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/22259926/viewspace-629453/,如需轉載,請註明出處,否則將追究法律責任。

相關文章