2014-11-14 37 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