To start, I found this post and used it as a reference. I'm attempting to subscribe to events from the View Model of my application. Doing this would allow me to easily execute code from my Model classes and perform various activities when backgrounding and foregrounding an application. This is something I utilize a lot in my existing Xamarin applications.
I started with the following code inside of my App.xaml.cs file:
protected override Window CreateWindow(IActivationState activationState)
{
Window window = base.CreateWindow(activationState);
window.Activated += (sender, eventArgs) => {
Models.Debug.Log(LogType.Info, "Activated");
};
window.Deactivated += (sender, eventArgs) => {
Models.Debug.Log(LogType.Info, "Deactivated");
};
return window;
}
This worked as intended and logged everything to the Output window. (Debug.Log is my own little utility I built for logging)
I then updated the code in the App file to the following, similar to the previously mentioned Stack Overflow post as well as another MAUI Blog post.
public static Window Window { get; private set; }
protected override Window CreateWindow(IActivationState activationState)
{
Window window = base.CreateWindow(activationState);
Window = window;
return window;
}
Then I went to the view model for my apps main page and added this:
var window = App.Window;
window.Activated += (s, e) =>
{
Debug.Log(LogType.Info, "Activated");
};
window.Deactivated += (s, e) =>
{
Debug.Log(LogType.Info, "Deactivated");
};
I end up getting an object reference error.
The confusion here is that the CreateWindow method is clearly getting called, since I can see the logs when I use the first version of the code I posted above. So why would window not be set to an instance when the app has already advanced to loading the first content page?
Any advice on what to try next is appreciated. If there's a better way to go about managing lifecycles in MAUI then please let me know.