日期:2014-05-17  浏览次数:20999 次

c# winform中 如何在另一个类中 修改form类中的控件

//form类是这样的
public partial class Main : Form
{
    //...
    public Main()
    {
        InitializeComponent();
    }

    public void Add(string log)
    {
        textBox1.Text += log + "\r\n";
    }
    //...
}


//另一个类是这样的
public class Watcher
{
    //...
    public Watcher()
    {
        fileSystemWatcher.Path = folderPath;
        fileSystemWatcher.Created += new FileSystemEventHandler(fileSystemWatcher_Created);
        fileSystemWatcher.EnableRaisingEvents = true;
    }

    void fileSystemWatcher_Created(object sender, FileSystemEventArgs e)
    {
        //想要在这里通过调用Main类中的Add方法修改界面中的控件 如何实现?
    }
    //...
}

------解决方案--------------------
建议不要"在另一个类中 修改form类中的控件"。
而是form类侦听另一个类的事件变化,改变自己。

    public Main()
    {
        InitializeComponent();
        watcher.XXXchanged += (sender, e)
        {
            textbox1.Text = ...;
        }
    }

------解决方案--------------------
//form类是这样的
public partial class Main : Form
{
    //...
    public Main()
    {
        InitializeComponent();
    }

    public void Add(string log)
    {
        Watcher w=new Watcher();
        w.main=this; //这里把this传给Main属性

        textBox1.Text += log + "\r\n";
    }
    //...
}


//另一个类是这样的
public class Watcher
{
    //...
    public Watcher()
    {
        fileSystemWatcher.Path = folderPath;
        fileSystemWatcher.Created += new FileSystemEventHandler(fileSystemWatcher_Created);
        fileSystemWatcher.EnableRaisingEvents = true;
    }

    void fileSystemWatcher_Created(object sender, FileSystemEventArgs e)
    {
    &nb