Search code examples
c#wpfwindowdispose

How to avoid multiple event fire when WPF page is opened again?


I have a frame and few pages in my WPF application.

My navigation is controlled by buttons. On each button I have click handler that creates new page with some parameters:

private void ButtonProductionAuto_OnClick(ref TechModbus, RoutedEventArgs e)
{
    FrameMain.Content = new PageProductionAuto(someobject, this);
}

private void ButtonProductionManual_OnClick(ref TechModbus, RoutedEventArgs e)
{
    FrameMain.Content = new PageProductionManual(someobject, this);
}

When I'm switching between pages - previous pages still exist in memory and they react on some custom events.

(edit)

This is my code related with events:

public PageProductionAuto(ref TechModbus modbus, MainWindow wnd)
{        
    // ...

    wnd.KeyDown += Wnd_KeyDown;
    wnd.KeyUp += Wnd_KeyUp;
    m.OnReadFinished += Modbus_OnReadFinished;

    // ...
}

How can I dispose these pages or how can I avoid double-fire on my events when page is opened second time?


Solution

  • You should unregister the events on leaving the page.

    GarbageCollector will then "dispose" (it's actually not a dispose) by itsself when there are no more references on those objects(PageProductionAuto and PageProductionManual).

    Quoting MS: The reason WPF controls don't implement IDisposable is because they have nothing to dispose. They have no handle to clean up, and no unmanaged resources to release. To ensure your memory is cleaned up, just make sure nothing has a reference to the controls once you're finished with them.