2014-11-14 35 views
1

我有3個事件與拖放有關。設置發件人事件變量

object originalSender; 

    private void lstBox_MouseDown(object sender, MouseEventArgs e) 
    { 
     ListBox curListBox = sender as ListBox; 
     if (curListBox.SelectedItem == null) return; 
     //this.lstLeft.DoDragDrop(this.lstLeft.SelectedItem, DragDropEffects.Move); 
     curListBox.DoDragDrop(curListBox.SelectedItem, DragDropEffects.Copy); 
     originalSender = sender; 
    } 

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

    private void lstBox_DragDrop(object sender, DragEventArgs e) 
    { 
     var obj = e.Data.GetData(e.Data.GetFormats()[0]); 

     if (typeof(DataGridViewColumn).IsAssignableFrom(obj.GetType())) 
     { 
      ListBox curListBox = sender as ListBox; 
      Point point = curListBox.PointToClient(new Point(e.X, e.Y)); 
      int index = curListBox.IndexFromPoint(point); 
      if (index < 0) 
       if (curListBox.Items.Count > 0) 
        index = curListBox.Items.Count - 1; 
       else 
        index = 0; 
      ((ListBox)(originalSender)).Items.Remove(obj); 
      curListBox.Items.Insert(index, obj); 
     } 

問題是,當運行lst_DragDrop方法時,「originalSender」爲null。我確定它是因爲我引用了垃圾收集的發送者對象,因此它是空的。我怎樣才能引用發件人的列表框。

我有3個ListBoxes都使用這種方法,所以我需要知道哪一個被挑選。

+0

嘗試列表框originalSender =(ListBox)sender; – Sybren 2014-11-14 22:31:14

+0

爲什麼不使用返回的*私有變量*?或者更好的是,封裝字段(Property)用於存儲整個生命週期中的用法值?雖然你可以做* instantation *,它應該看起來像'((ListBox)sender)。「。 – Greg 2014-11-14 22:32:09

+0

'sender'和'originalSender'有什麼區別? 'sender'應該讓你控制事件被觸發。這不是你需要的嗎? – shasan 2014-11-14 22:33:19

回答

1

嘗試在撥打DoDragDrop之前撥打originalSender = sender聲明; DoDragDrop在同一線程上啓動一個新的消息泵,所以當前語句不會執行,直到拖放操作結束。


補充說明:

我相信它,因爲我引用發送對象獲取垃圾回收,因此空

不,那是不可能的。你明白了:垃圾收集器從不將對象引用設置爲null,它只是收集不再被引用的對象。

+0

就是這樣,謝謝。 – BrinkDaDrink 2014-11-14 22:44:41

+0

感謝您對垃圾回收的澄清。看着它更多,理解。 – BrinkDaDrink 2014-11-20 15:35:07