Problem 1: Reference to the MainWindow.cs:
In object oriented programming you decouple the components for better overview, testability inheritance, etc... But you have to think about how you propagate the reference between the objects. What i mean is: the instance of class dosomething has to have a reference to the MainWindow to be able to update anything on it.
What you do now is: you create a new instance of MainWindow in the method and change the status (but not of the MainWIndow which is in reality visualized)
You can pass a reference to the actual MainWindow to the function. This is called Dependency Injection. Normally you would inject only an interface which is implemented by the MainWindow class, so also another class could use this functionality, but this is leading too far.
Quick fix:
public void Do(MainWindow window)
{
window.status_textblock = "test";
for (int i = 1; i<1000000; i++)
i += i;
Thread.sleep(100);
window.status_textblock = i.tostring();
}
and call it on the MainWindow like that:
new Dosomething().Do(this);
But this will still not work, as the Thread is blocked (with Thread.Sleep) and will only visualize the results at the end when the Thread is free to render the Visualization.
Problem 2: You have to run it in another Thread / Task
public void Do(MainWindow window)
{
Task.Factory.StartNew(() => {
window.status_textblock = "test";
for (int i = 1; i < 1000000; i++)
i += i;
Thread.sleep(100);
window.status_textblock = i.tostring();
});
}
but wait this will not work either, because you try to update the UI from another thread which is not allowed
Problem 3: Update the UI with the STA thread
In the MainWindow class you create a method which updates the status text on the STA thread (STA thread is the only one which is allowed to update anything on the UI).
public void UpdateStatus(string status)
{
if (this.Dispatcher.CheckAccess())
this.status_textblock = status;
else
this.Dispatcher.Invoke(new Action<string>(UpdateStatus), status);
}
and from the DoSomething class you call the UpdateStatus Method:
public void Do(MainWindow window)
{
Task.Factory.StartNew(() => {
window.UpdateStatus("test");
for (int i = 1; i < 1000000; i++)
i += i;
Thread.sleep(100);
window.UpdateStatus(i.tostring());
});
}
--> it works!