Accessing property from multiple Classes (MVVM WPF application)
mrw
201
Reputation points
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
Sign in to answer