none
[Silverlight Tips] DragAndDrop RRS feed

  • 일반 토론

  •  

    질문

     

    Silverlight에서 마우스 이벤트를 이용해서 Drag And Drop을 구현할 수 있습니다.

     

    답변

     

    Step 1 : Layout 작성

    MainPage.XAML

    <Canvas>
        <Rectangle Fill="Aqua" 
                    Width="100"
                    Height="100"
                    MouseLeftButtonDown="Rectangle_MouseLeftButtonDown"
                    MouseMove="Rectangle_MouseMove"
                    MouseLeftButtonUp="Rectangle_MouseLeftButtonUp"
                    />
    </Canvas>

     

     

    Step 2 : 전역 변수 작성

    MainPage.XAML.CS

    #region Field
    private Point _lastPoint;
    private double _offsetX;
    private double _offsetY;
    private bool _isDragging = false;
    #endregion Field

     

    Step 3 : Event Handler 작성


    MainPage.XAML.CS


    #region EventHandler
    private void Rectangle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        Rectangle curObject = sender as Rectangle;
     
        curObject.CaptureMouse();
     
        //현재 포인트값을 임시변수에 저장
        _lastPoint = e.GetPosition(null);
        double cx = (double)curObject.GetValue(Canvas.LeftProperty);
        double cy = (double)curObject.GetValue(Canvas.TopProperty);
     
        _offsetX = _lastPoint.X - cx;
        _offsetY = _lastPoint.Y - cy;
     
        _isDragging = true;
     
    }
     
    private void Rectangle_MouseMove(object sender, MouseEventArgs e)
    {
        Rectangle curObject = sender as Rectangle;
     
        if (_isDragging == true)
        {
            Point pt = e.GetPosition(null);
     
            //이동한 수치 계산
            double x = pt.X - _lastPoint.X;
            double y = pt.Y - _lastPoint.Y;
     
            double cx = (double)curObject.GetValue(Canvas.LeftProperty);
            double cy = (double)curObject.GetValue(Canvas.TopProperty);
     
            //이동한 수치만큼 현재 객체 이동
            curObject.SetValue(Canvas.LeftProperty, cx + x);
            curObject.SetValue(Canvas.TopProperty, cy + y);
     
            _lastPoint = pt;
        }
    }
     
     
    private void Rectangle_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        Rectangle curObject = sender as Rectangle;
     
        _isDragging = false;
        curObject.ReleaseMouseCapture();
    }
    #endregion EventHandler

     

    Solution Explorer

     

    참고 자료

     

    UIElement.CaptureMouse Method

    http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=EN-US&k=k(SYSTEM.WINDOWS.UIELEMENT.CAPTUREMOUSE);k(TargetFrameworkMoniker-%22SILVERLIGHT%2cVERSION%3dV4.0%22);k(DevLang-CSHARP)&rd=true


    UIElement.ReleaseMouseCapture Method

    http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=EN-US&k=k(SYSTEM.WINDOWS.UIELEMENT.RELEASEMOUSECAPTURE);k(TargetFrameworkMoniker-%22SILVERLIGHT%2cVERSION%3dV4.0%22);k(DevLang-CSHARP)&rd=true

    2011년 9월 15일 목요일 오전 4:51
    중재자