Is it possible to reference MainWindow.cs from another class?

I have a WPF / C # program with several classes, and in the MainWindow.cs class there are user controls that I would like to update with the calculation status occurring inside other classes. After I started looking for and borrowing examples, I figured out how to set up an event inside another class and call it when something changed. Then, while the main class has a handler associated with this event, I could update the UI stuff (status bars, etc.) accordingly. Below is a stripped down version of what I'm doing:

namespace Program { public partial class MainWindow : Window { public void SetUpHandler() { TestA.WorkerProgressThingie += new ProgressChangedEventHandler(TestA_ProgressChanged); } void TestA_ProgressChanged(object sender, ProgressChangedEventArgs e) { progressBar1.Value = e.ProgressPercentage } } public class TestA { public static event ProgressChangedEventHandler WorkerProgressThingie; public static void SomeFunction() { int value = 0; //...(some boring code that does something here) ProgressChangedEventArgs e = new ProgressChangedEventArgs(value, null); if (WorkerProgressThingie != null) WorkerProgressThingie.Invoke(null, e) } } } 
  • Can't you just call the progressBar property from another class? (i.e. MainWindow.progressBar.Value)?
  • What is the purpose of the "object sender" parameter when triggering an event, and how should it be used in normal mode? The examples I see always use "null".

Thanks!

+4
source share
1 answer

1) Yes, you can access any part of any class if it is declared public. In this case, you can declare progressBar public control, and everything that has a link to class MainWindow , can play with it. HOWEVER, that would be pretty bad practice. Instead, you can bind to some β€œvalue” that updates with respect to the current progress of the activity and allows the MainWindow class to worry about how it represents this change (in this case, updating the ProgressBar)

2) object sender in all cases implies a reference to the object that raised the event, so the consumer of the event knows where the event came from. Using null is also bad IMO practice, and in general the object that raises the event should do it like this:

 SomeEvent(this, someEventArgs); 
+2
source

All Articles