2009-01-30 3 views
12

목록 상자와 트리 뷰가있는 winform이 있습니다.C# 목록 상자에서 트리보기로 드래그 앤 드롭

일단 목록 상자가 항목으로 채워지면 목록 상자에서 여러개 또는 단일 항목을 끌어서 트리보기의 노드에 놓기를 원합니다.

누군가가 C#에서 좋은 예를 들고 있다면 좋을 것입니다.

+1

게시물을 편집하여 문제의 어떤 부분을 정확하게 알려줄 수 있습니까? 여기 사람들은 "ples send the codz"형식 질문에 잘 응답하지 않는 경향이 있습니다. –

답변

23

드래그 앤 드롭으로 뒤죽박죽이 된 지 오래되었으므로 간단한 샘플을 작성하겠습니다.

기본적으로 왼쪽에는 목록 상자가 있고 오른쪽에는 트리보기가있는 양식이 있습니다. 그런 다음 위에 버튼을 놓습니다. 버튼을 클릭하면 다음 10 일간의 날짜가 목록 상자에 나타납니다. 또한 TreeView를 부모 노드 2 개와 자식 노드 2 개로 채 웁니다. 그런 다음 모든 드래그/드롭 이벤트를 처리해야 작동합니다.

public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
      this.treeView1.AllowDrop = true; 
      this.listBox1.AllowDrop = true; 
      this.listBox1.MouseDown += new MouseEventHandler(listBox1_MouseDown); 
      this.listBox1.DragOver += new DragEventHandler(listBox1_DragOver); 

      this.treeView1.DragEnter += new DragEventHandler(treeView1_DragEnter); 
      this.treeView1.DragDrop += new DragEventHandler(treeView1_DragDrop); 

     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      this.PopulateListBox(); 
      this.PopulateTreeView(); 
     } 

     private void PopulateListBox() 
     { 
      for (int i = 0; i <= 10; i++) 
      { 
       this.listBox1.Items.Add(DateTime.Now.AddDays(i)); 
      } 
     } 

     private void PopulateTreeView() 
     { 
      for (int i = 1; i <= 2; i++) 
      { 
       TreeNode node = new TreeNode("Node" + i); 
       for (int j = 1; j <= 2; j++) 
       { 
        node.Nodes.Add("SubNode" + j); 
       } 
       this.treeView1.Nodes.Add(node); 
      } 
     } 

     private void treeView1_DragDrop(object sender, DragEventArgs e) 
     { 

      TreeNode nodeToDropIn = this.treeView1.GetNodeAt(this.treeView1.PointToClient(new Point(e.X, e.Y))); 
      if (nodeToDropIn == null) { return; } 
      if(nodeToDropIn.Level > 0) 
      { 
       nodeToDropIn = nodeToDropIn.Parent; 
      } 

      object data = e.Data.GetData(typeof(DateTime)); 
      if (data == null) { return; } 
      nodeToDropIn.Nodes.Add(data.ToString()); 
      this.listBox1.Items.Remove(data); 
     } 

     private void listBox1_DragOver(object sender, DragEventArgs e) 
     { 
      e.Effect = DragDropEffects.Move; 
     } 

     private void treeView1_DragEnter(object sender, DragEventArgs e) 
     { 
      e.Effect = DragDropEffects.Move; 
     } 

     private void listBox1_MouseDown(object sender, MouseEventArgs e) 
     { 
      this.listBox1.DoDragDrop(this.listBox1.SelectedItem, DragDropEffects.Move); 
     } 


    } 
+0

정말 고마워요. Mono에서 (적어도 OSX에서는) 드래그 앤 드롭 "효과"를 얻지 못한다는 것을 확인하기 위해 코드 예제가 필요했습니다. 위대하고 완전한 예는 나에게 엄청난 노동을 안겨다 주었다. –

3

GetItemAt (포인트 포인트) 함수를 사용하여 X, Y 위치를리스트 뷰 항목으로 변환하려고합니다.

여기에 대해서는 매우 좋은 기사 인 Drag and Drop Using C#입니다.

드래그하는 동안 항목을 끌 수 있도록하려면 COM ImageList를 사용해야합니다. 자세한 내용은 다음 문서 Custom Drag-Drop Images Using ImageLists에 나와 있습니다.