简体   繁体   中英

Win32 events + WPF + MVVM

SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch);

I'm building a wpf application, that times the time between workstation locks and unlocks But I'm having a hard time implementing it without putting in in mainwindow codebehind

the code im using for starting and stopping the timer

SystemEvents.SessionSwitch +=
                new SessionSwitchEventHandler(SystemEvents_SessionSwitch);
private static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
        {
            if (e.Reason == SessionSwitchReason.SessionLock)
            {
                //Start Timer
            }
            else if (e.Reason == SessionSwitchReason.SessionUnlock)
            {
                //Stop Timer -> show window
            }
        }

problem is, this event resides in Microsoft.Win32 - which I cannot seem to reference in XAML (if i could I would have hooked it up to an ICommand instead)

so all you MVVM experts out there, what do I do about this? Do i keep it in mainwindow codebehind? or can i actually reference Win32 in XAML

and a side question... the timer logic - do i keep this in seperate class and store the value in the model or? needless to say - I'm fairly new to MVVM

The core principal behind MVVM is unit-testability and separation of responsibility. This is typically enforced by making sure that the ViewModel has no knowledge of the layers above it (ie the "View") nor should it interact directly with any platform-specific classes (ie Microsoft.Win32.SystemEvents ).

One approach I might suggest would be be to create your own ISystemEvents interface, which exposes only the events you'd like your ViewModel to handle. The implementation of this interface could be considered to be part of your 'Model' layer, and would essentially wrap the desired events from Microsoft.Win32.SystemEvents . Your application would ' inject ' the interface as part of the ViewModel's initialization.

public interface ISystemEvents
{
    event EventHandler<SessionSwitchEventArgs> SessionSwitch;
}

//Pass this implementation to your viewmodel, via the constructor
public class MySystemEvents : ISystemEvents
{
    public event EventHandler<SessionSwitchEventArgs> SessionSwitch
    {
        add { Microsoft.Win32.SystemEvents.SessionSwitch += value; }
        remove { Microsoft.Win32.SystemEvents.SessionSwitch -= value; }
    }
}

public class MyViewModel
{
    public MyViewModel(ISystemEvents systemEvents)
    {
        //Store the instance of your object here, and subscribe to the desired events
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM