2

In a WPF application I have, I have a control that is central to the application. This control, called ArtView, is visible for the entire lifetime of the main window. It performs hardware accelerated rendering, and in order to avoid bogging down the UI thread, I set up an event loop in the OnLoaded handler for this control. Events such as mouse clicks, keyboard input, and scrolling are added to a queue that is then consumed by the event loop, but the problem I have is that I do not know how to end the event loop when the window is closed. When I close the window that contains the control, OnUnloaded does not fire, so what is the best way to disable the event loop when the control is no longer visible?

I am aware that I can do something like Window.GetWindow(this).Closing += OnWindowClosing; but that feels like a hack.

laptou
  • 6,389
  • 2
  • 28
  • 59
  • Seems related: https://stackoverflow.com/questions/1499477/wpf-window-close-not-triggering-usercontrol-unloaded-event and https://stackoverflow.com/questions/502761/disposing-wpf-user-controls – Manfred Radlwimmer Nov 28 '17 at 14:27
  • You think it "feels like a hack" to use a WindowClosing event handler to execute code when the window closes? Well, I don't want to invalidate your feelings. – 15ee8f99-57ff-4f92-890c-b56153 Nov 28 '17 at 14:34
  • 1
    @EdPlunkett I understand his argument to he honest. I'd want my controls to clean up after themselves too instead of doing that in the parent container. – Manfred Radlwimmer Nov 28 '17 at 14:37
  • Just tried a simple `IDisposable` implementation, but that doesn't seem to work either without some manual work from outside :( – Manfred Radlwimmer Nov 28 '17 at 14:48
  • 1
    Subscribe to the control's `IsVisibleChanged` event. Since your control is always visible, this event will fire only two times: on window shown and on window closed. This looks like another hack though. – dymanoid Nov 28 '17 at 14:59
  • @ManfredRadlwimmer I wouldn't call that "in the parent container" -- it's just an event; the window doesn't know what the handler's doing. I'd prefer to use the control's own "end of lifecycle" event if it had one, but this *is* the control cleaning up after itself. At least, it is if I'm correct in assuming that the code `Window.GetWindow(this).Closing += OnWindowClosing;` belongs to the control. – 15ee8f99-57ff-4f92-890c-b56153 Nov 28 '17 at 15:00

1 Answers1

0

dymanoid's solution of subscribing to IsVisibleChanged works flawlessly, and provides a more satisfying solution than depending on the Window for the cleanup of my control.

laptou
  • 6,389
  • 2
  • 28
  • 59