Accessing property from multiple Classes (MVVM WPF application)

mrw 201 Reputation points
2020-12-16T14:23:49.5+00:00

I have been trying to learn C# by creating a small app. Recently I have been trying to implement SessionEvent for screen lock/unlock to pause the timer. I am having a problem understanding how to access timer from App.xaml.cs. Currently while locking the screen, I am getting following error:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

SimpleTimer.Main.App.TimerViewModel.get returned null.

I understand that I need to initialize property, but how?

App.xaml.cs:

using Microsoft.Win32;
using SimpleTimer.ViewModels;
using System;
using System.Diagnostics;
using System.Windows;
using SimpleTimer.Models;
using log4net;
using System.Reflection;

namespace SimpleTimer.Main
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private ILog Logger { get; } =
            LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public App()
        {
        }

        private TimerViewModel TimerViewModel { get; }

        private void Run(object sender, StartupEventArgs e)
        {
            SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch);

            var mainWindow = new MainWindow() {
                DataContext = new ViewModel(new GeneralDataProvider())
            };

            mainWindow.Show();
        }

        public void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
        {
            if (e.Reason == SessionSwitchReason.SessionLock)
            {
                Debug.Print("I am locked: " + DateTime.Now);
                TimerViewModel.newProcess.TogglePause();
            }
            else if (e.Reason == SessionSwitchReason.SessionUnlock)
            {
                Debug.Print("I am unlocked: " + DateTime.Now);
                TimerViewModel.newProcess.TogglePause();
            }
        }
    }
}

Here is link to full project:
https://github.com/vadimffe/SimpleTimer

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,667 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,205 questions
XAML
XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
762 questions
{count} votes