WinRT: A method was called at an unexpected time. WinRT Information: An eventhandler has already been registered.
For a WinRT application I’m building I decided to support the Share charm. This is done through the use of the DataTransferManager class.
So in the constructor of my page, I added the following code to listen for Share requests:
This seems to work fine but when I moved to another page and navigated back afterwards, I always got the following error message:
“An exception of type 'System.InvalidOperationException' occurred in mscorlib.dll but was handled in user code. A method was called at an unexpected time.WinRT information: An event handler has already been registered”
I first tried to solve it by unregistering the event handler in the constructor before registering it but this didn’t help:
Instead you have to unregister the event when you navigate away from the page:
I don’t know if it’s a bug in the WinRT framework but it’s certainly unexpected behavior.
So in the constructor of my page, I added the following code to listen for Share requests:
_manager = DataTransferManager.GetForCurrentView(); _manager.DataRequested += manager_DataRequested;
“An exception of type 'System.InvalidOperationException' occurred in mscorlib.dll but was handled in user code. A method was called at an unexpected time.WinRT information: An event handler has already been registered”
I first tried to solve it by unregistering the event handler in the constructor before registering it but this didn’t help:
_manager = DataTransferManager.GetForCurrentView(); _manager.DataRequested -= manager_DataRequested; _manager.DataRequested += manager_DataRequested;
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) { var manager = DataTransferManager.GetForCurrentView(); manager.DataRequested -= manager_DataRequested; base.OnNavigatingFrom(e); }