본문 바로가기
백엔드기술/개발언어

[예제] 객체 끌어 놓기

by RevFactory 2008. 12. 1.

1. 새프로젝트 -> DragAndDropSimple 생성
2. XAML 코드
 그리드 대신 캔버스로 바꾼 후 사각형 하나를 추가시킨다.

 <UserControl x:Class="DragAndDropSimple.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="400" Height="300">
  <Canvas x:Name="rootCanvas"  >

    <!-- 이동할 사각형 개체 -->
    <Rectangle
    MouseLeftButtonDown="Handle_MouseDown"
    MouseMove="Handle_MouseMove"
    MouseLeftButtonUp="Handle_MouseUp"
    Canvas.Left="30" Canvas.Top="30" Fill="Red"
    Width="50" Height="50" />
  </Canvas>

</UserControl>



3. C#코드
마우스 왼쪽 버튼 다운시, 업시, 마우스 이동시에 대한 이벤트를 처리해준다.

 // 마우스 클릭으로 이동중인지 체크를 위한 변수와 포인터 위치를 위한 변수
bool isMouseCaptured;
double mouseVerticalPosition;
double mouseHorizontalPosition;

public void Handle_MouseDown (object sender, MouseEventArgs args)
{
    Rectangle item = sender as Rectangle;
    mouseVerticalPosition = args.GetPosition(null).Y;
    mouseHorizontalPosition = args.GetPosition(null).X;
    isMouseCaptured = true;
    item.CaptureMouse();
}

public void Handle_MouseMove(object sender, MouseEventArgs args)
{
    Rectangle item = sender as Rectangle;
    if (isMouseCaptured)
    {

        // 개체의 현재 위치를 계산
        double deltaV = args.GetPosition(null).Y - mouseVerticalPosition;
        double deltaH = args.GetPosition(null).X - mouseHorizontalPosition;
        double newTop = deltaV + (double)item.GetValue(Canvas.TopProperty);
        double newLeft = deltaH + (double)item.GetValue(Canvas.LeftProperty);

        // 개체의 위치 적용
        item.SetValue(Canvas.TopProperty, newTop);
        item.SetValue(Canvas.LeftProperty, newLeft);

        // 멤버 변수 갱신
        mouseVerticalPosition = args.GetPosition(null).Y;
        mouseHorizontalPosition = args.GetPosition(null).X;
    }
}

public void Handle_MouseUp(object sender, MouseEventArgs args)
{
    Rectangle item = sender as Rectangle;
    isMouseCaptured = false;
    item.ReleaseMouseCapture();
    mouseVerticalPosition = -1;
    mouseHorizontalPosition = -1;
}


4. 참고
 - GetPosition( ) : 전체 플러그인 좌표계를 기준으로 지정시 element 매개변수를 null로 설정
 - CaptureMouse( ) / ReleaseMouseCapture( ) : 마우스를 캡쳐한 개체는 마우스 포인터가 해당 경계내에 있는지 여부에 관계없이 마우스 입력을 받을 수 있다.