首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

c# winform中 怎么在另一个类中 修改form类中的控件

2013-04-12 
c# winform中 如何在另一个类中 修改form类中的控件//form类是这样的public partial class Main : Form{//

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)
    {
       if(main!=null)


         main.Add();

        //想要在这里通过调用Main类中的Add方法修改界面中的控件 如何实现?
    }
    //...

   public Main main{get;set;} //加一个Main属性
}

热点排行