1

I am trying to limit the number of times an event can be subscribed to by the same function. The idea is that I want to be able to check whether the event has already been subscribed to, and reject any duplicate subscriptions.

I have done this before in WPF, using a self declared event:

private static EventHandler<string> dataToDisplayEvent;   // Declare new event

public static event EventHandler<string> DataToDisplayEvent
{
    add
     {
        if (dataToDisplayEvent == null || 
           !dataToDisplayEvent.GetInvocationList().Contains(value)) dataToDisplayEvent += value;
     }
     remove
     {
        dataToDisplayEvent -= value;
     }
}

Simple enough, However I am now trying it with Xamarin Forms (although I don't think this should make any difference) and with an even from a plugin rather than a self declared event.

The plugin I'm using is Plugin.BLE https://github.com/xabre/xamarin-bluetooth-le

public event EventHandler<BluetoothStateChangedArgs> StateChanged
{
    add
    {
        if (!CrossBluetoothLE.Current.StateChanged.GetInvocationList().Contains(value))
        {
            CrossBluetoothLE.Current.StateChanged += value;
        }
    }
    remove => CrossBluetoothLE.Current.StateChanged -= value;
}

However this keeps giving me the message "The event 'IBluetoothLE.StateChanged' can only appear on the left hand side of += or -="

I'm pretty sure that this is to do with the implementation of the event in the plugin - however, I am trying to figure out an effective (and hopefully elegant) workaround to this and to understand why I cannot use this approach with the plugin.

Edit - this question was previously closed due to being a duplicate - however the original question as to why the plugin GetInvocationList() cannot be called is not answered in the so-called "duplicate".

Duplicate: -event- can only appear on the left hand side of += or -=

The duplicate is a separate question about a backing store - my question is why GetinvocationList() cannot be called on the event from the BLE plugin I am using.

Thanks

Bart
  • 63
  • 1
  • 12
  • 3
    if your question was closed as a duplicate, then vote to reopen it, don't post yet ANOTHER duplicate question – Jason Apr 12 '21 at 19:05
  • I can't find the option to do that - I did look. I will look again. The info box suggested that I ask another question if my original wasn't answered, so that's what I did – Bart Apr 12 '21 at 19:05
  • have you tried putting the `remove` case in a block like the `add` case, instead of using the `=>` accessor? – Jason Apr 12 '21 at 19:07
  • @Jason Yes, but that but that makes no difference. The issue is with calling GetInvocationList() on the StateChanged EventHandler. – Bart Apr 12 '21 at 19:12

0 Answers0