访问表单控件,例如来自其他类的openfiledialog

时间:2015-03-08 05:18:35

标签: c#

我有使用openfileDialog1

的MainForm
public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
    }

    //I tried to return OpenFileDialog like this
    public OpenFileDialog ReturnOpenFileDialog()
    {
        return openFileDialog1;
    } 

  }

和类文件Facade.cs

public class Facade
{
   //How can I access to OpenFileDialog1 here?      

       /*Like: 
        openFileDialog1.Filter = "DLL|*.dll";
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {....*/
}            

两个文件的命名空间相同,CakeFactory。 如何从Facade.cs访问控制MainForm的OpenFileDialog?

2 个答案:

答案 0 :(得分:0)

我建议在单独的实用程序类中定义ReturnOpenFileDialog(),然后创建该实用程序类的实例,并在需要时调用此方法。

另一种选择是使ReturnOpenFileDialog()静态,然后你可以在Facade.cs中将其称为MainForm.ReturnOpenFileDialog()

答案 1 :(得分:0)

以下是示例代码

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        FormInstances.frm = this;
        new Facade();
    }


    public OpenFileDialog ReturnOpenFileDialog()
    {
        return openFileDialog1;
    }
}
public static class FormInstances
{
    public static Form1 frm { get; set; }
}
public class Facade
{
    public Facade()
    {
       OpenFileDialog f= FormInstances.frm.ReturnOpenFileDialog();
        f.Filter="DLL|*.dll";
        f.ShowDialog();

    }
}