I've Got 2 classes:
One Service which creates a FileSystemWatcher that fires an event when the watched File is saved by Word. And one UserControl that has got some functions I need to execute when the SaveEvent is fired.
How can I react to the SaveEvent in the UserControl?
I would create an event in the Service which will be raised when the FileSystemWatcher is raised. The Service should wrap the FileSystemWatcher . The parent of both objects will call a method on the UserControl.
For example: (PSEUDO)
class MyProgram
{
Service svc;
UserControl ctrl;
public MyProgram()
{
// create the control
ctrl = new UserControl();
// create the service
svc = new Service();
svc.SaveEvent += FileChanges;
/////// you might construct something like: _(do not use both)_
svc.SaveEvent += (s, e) => ctrl.FileIsSaved(e.Filename);
}
private void FileChanges(object sender, ServiceFileChangedEventArgs e)
{
ctrl.FileIsSaved(e.Filename);
}
}
class Service
{
// FileSystemWatcher
private FileSystemWatcher _watcher;
public Service() // constructor
{
// construct it.
_watcher = new FileSystemWatcher();
_watcher.Changed += Watcher_Changed;
}
// when the file system watcher raises an event, you could pass it thru or construct a new one, whatever you need to pass to the parent object
private void Watcher_Changed(object source, FileSystemEventArgs e)
{
SaveEvent?.Invoke(this, new ServiceFileChangedEventArgs(e.FullPath)); // whatever
}
public event EventHandler<SaveEventEventArgs> SaveEvent;
}
class SaveEventEventArgs : EventArgs
{
// filename etc....
}
This is just some pseudo example code. But the important thing is, Your Program
/ Usercontrol
should NOT depend on the FileSystemWatcher
. Your Service
should wrap it. So whenever you decide to change the FileSystemWatcher
to (for example) a DropBoxWatcher
, the rest of the program isn't broken.
Create a delegate for that event to handle it.
myClass.SaveEvent += DelegateMethod();
public void DelegateMethod(object sender, SaveEventArgs e)
{
//do stuff
//run your handler code
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.