从另一个类访问事件初始化变量

时间:2015-02-12 15:41:41

标签: c# winforms events

我正在尝试使用由另一个类的拖放事件初始化的变量(fileName)。

理想情况下,如果fileName是一种可以通过拖放事件永久更新的全局变量,那就太好了。然后我可以从另一个类调用已更新的变量。有可能吗?

public void DragDropRichTextBox_DragDrop(object sender, DragEventArgs e)
{
    string[] fileName = e.Data.GetData(DataFormats.FileDrop) as string[];

    if (fileName != null)
    {
        foreach (string name in fileName)
        {
            try
            {
                AppendText(BinaryFile.ReadString(name);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}

变量fileName包含拖动文件的目录/目录。我想在自定义数据打印功能中使用该目录,在单独的类中,需要文件的路径。

1 个答案:

答案 0 :(得分:0)

如果我正确理解了这个问题,那么以下选项可能会为您完成这项工作:

  1. 将FileNames公开为可由其他类引用的属性。
  2. 使用您自己的事件转发您在DragDropRichTextBox_DragDrop事件句柄上接收的数据,例如:

    public class YourClass
    {
         // The other class would register to this event 
         public event Action<string[]> TextBoxDropDown;
    
         public void DragDropRichTextBox_DragDrop(
            object sender,DragEventArgs e)
         { 
            string[] fileNames = e.Data.GetData(DataFormats.FileDrop) 
                                   as string[];
            if (fileNames != null&&TextBoxDropDown !=null)
             {
                 TextBoxDropDown(fileNames);    
             }
         }
    }
    
相关问题