Search code examples
c#xamlwindows-phone-8windows-phone

Proximity event is registered multiple times


I have this application that is listening for arrival of NFC devices. It's based of the example from Microsoft:

http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh465221.aspx

Windows.Networking.Proximity.ProximityDevice proximityDevice;

public MainPage()
{
    InitializeComponent();

    proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();

    if (proximityDevice != null)
    {
        proximityDevice.DeviceArrived += ProximityDeviceArrived;
    }
    else
    {
        MessageTextBlock.Text += "Failed to initialize proximity device.\n";
    }
}

This is implemented in my MainPage.xaml. My problem is that if I navigate to another page, and then go back by pressing the back button (im not overwriting the function) I now got multiple events it seems.

So when a device arrives before navigating it register it once, after I've been to another .xaml page and gone back the DeviceArrived is triggered multiple times even if only one device arrived.

Do I have to lock it some way?


Solution

  • The design pattern you should be following in XAML based frameworks for static events is to register in the OnNavigatedTo method override and unregister in the OnNavigatedFrom method override.

    private ProximityDevice proximity = ProximityDevice.GetDefault();
    
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        if (proximity != null)
        {
            proximity.DeviceArrived += proximity_DeviceArrived;
        }   
    
        base.OnNavigatedTo(e);
    }
    
    protected override void OnNavigatedFrom(NavigationEventArgs e)
    {
        if (proximity != null)
        {
            proximity.DeviceArrived -= proximity_DeviceArrived;
        }   
    
        base.OnNavigatedFrom(e);
    }
    

    Or alternatively for a more architecturally sound solution, register to static events in a singleton class and translate those into Messages for Messenger/EventAggregator/etc.