读书人

c# winform中 怎么在另一个类中 修改f

发布时间: 2013-04-12 18:33:11 作者: rapoo

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属性
}

读书人网 >C#

热点推荐