Search code examples
c#wpfvisual-studioloopsprogram-entry-point

In a WPF project, how do I initialize my Window and controls and then jump into a main loop?


Apologies if the question is poorly phrased, new to C#. I'm trying to make a text adventure. I've already written all the underlying logic, and decided to try and use a WPF for basic graphics. So I initialize the window with all the controls I need and then loop through my main loop until you trigger an exit. I initially tried putting the loop right after initializing the window.

public MainWindow()
{
    InitializeComponent();
    Game.Logic();
}

This didn't really work well as the Window stopped initializing at all. So I googled around a bit and tried using a Loaded Event. Once I did that, the Window pops up when I run the code, but none of the controls appear and the window is frozen. The same problem persisted when I tried to use a Loaded Event for the controls themselves. While there may be some kind of bug in my Game Loop, I think the Window should at least be able to initialize all its controls if I'm jumping into the Loop correctly. Would the right thing to do be to go into the App file and use a Loaded Event there? Or am I just completely out of line somehow?


Solution

  • You're pretty far out of line.

    By executing a tight loop on the UI thread, you are killing any chance of the UI ever updating, even if you got past your current roadblocks. As far as Windows is concerned; you are "frozen".

    You need to run your logic loop on another thread and use Dispatcher.BeginInvoke to get any UI updates (and only UI updates) back onto the UI thread. While typically not as useful in game contexts, also consider using the MVVM pattern with Bindings as its harder to fall into this trap.

    For a text adventure, I would strongly recommend the MVVM pattern as all of your elements are easily represented as bound items/collections. Plus, it gets you into good modern development practices :)