Frage

I´ve a NavigationWindow with some pages. I navigate from one to another with buttons, and go back function of navigation window. My problem is I use a descriptor in some of the pages when they load, and I´d like to dispose it when you use go back function in navigationwindow (in fact the "descriptor" is Kinect, and when the page loads, it starts Kinect with sensor.start(), and I want to stop it when going back, sensor.stop()... but I think it´s the same as a file descriptor for this issue and much more people has worked with file descriptors).

Is there any way to extend the GoBack function in the page to dispose descriptors (in my code I only need to call sensor.stop(); )?

Thanks in advance

War es hilfreich?

Lösung 2

Ok, I found how to do a workaround. It also applies to the question: how to dispose an object in WPF. It´s weird all posts about dispose objects in WPF talk about GC and that you can´t dispose it yourself. Yes, GC dispose objects automatically, but when he wants. But maybe you want to dispose inmediately, or you have an object that needs previous operations before dispose. In my case, Kinect needs to be stopped before dispose (you can dispose without stopping, but kinect ir sensor is still working). And GC is not solution because I need to stop it before dispose.

So, the solution:

public partial class MyClass : Page
{
    private KinectSensor sensor;

    public MyClass()
    {
        InitializeComponent();
        this.Loaded += (s, e) =>  { NavigationService.Navigating += NavigationService_Navigating; };

        // What you want to add to the constructor
        // I want to start Kinect
        sensor = KinectSensor.KinectSensors.FirstOrDefault(k => k.Status == KinectStatus.Connected);
        sensor.Start();

    }

    public void NavigationService_Navigating(object sender, NavigatingCancelEventArgs e)
    {
        if (e.NavigationMode == NavigationMode.Back)
        {
            // What you want to do.
            // I want to stop and dispose Kinect
            if (sensor != null)
            {
                sensor.Stop();
                sensor.Dispose();
            }
        }
    }
}

Andere Tipps

My suggestion in the comment was based on windows phone development experience.. but after i tried applying that solution in wpf using navigationwindow, i found nothing like OnNavigatedTo/OnNavigatedFrom in WP/silverlight.

But i found Navigating event of NaviagtionWindow can be used instead. In that event, you can get this.CurrentSource which is Page2 (if you navigate back from Page2 to Page1) and dispose descriptors in that Page.

Hope this work.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top