1

I was trying to add a custom event to my custom control in Xamarin.Forms. Please take a look at the code below:

public delegate void ImageSelectedHandler(object sender, EventArgs e);
public static event ImageSelectedHandler OnImageSelected;

private void OnImageBtnTapped(object sender, EventArgs e)
{
   if (OnImageSelected != null) 
   {
        OnImageSelected(sender,e);
   }
}

In the page which is using the control:

SelectMultipleBasePage<ListItems>.OnImageSelected += ListPage_OnImageSelected;

void ListPage_OnImageSelected(object sender, EventArgs e)
{
  //code here
}

I could access the event by using the above code. But I would like to use the control on different pages. On different pages different OnImageSelected even will behave differently. And hence I would like to have something like this:

SelectMultipleBasePage<ListItems> multiPage = new SelectMultipleBasePage<ListItems>(items);
multiPage.OnImageSelected += ListPage_OnImageSelected;

But when I do that I get error:

Cannot be accessed with an instance reference; qualify it with a type name instead

What am I doing wrong in accessing the event?

Sven-Michael Stübe
  • 14,560
  • 4
  • 52
  • 103
Arti
  • 2,993
  • 11
  • 68
  • 121
  • 2
    By making the event static ! u r making it local to this class only , when u want to access it in another class . u will have to access it as Myclassname.OnImageSelected – Saket Kumar Apr 22 '16 at 07:21

1 Answers1

1

Just remove the static.

public event ImageSelectedHandler OnImageSelected;

Then you can call

SelectMultipleBasePage<ListItems> multiPage = new SelectMultipleBasePage<ListItems>(items);
multiPage.OnImageSelected += ListPage_OnImageSelected;

Of course you have to change the static call, too.

Sven-Michael Stübe
  • 14,560
  • 4
  • 52
  • 103
  • It doesn't work for me. It gives me error: `Error 14 Cannot access a non-static member of outer type 'AppName.SelectMultipleBasePage' via nested type 'AppName.SelectMultipleBasePage.WrappedItemSelectionTemplate' – Arti Apr 22 '16 at 06:52
  • Could you please look at the my previous question: [link](http://stackoverflow.com/questions/36714348/how-to-create-an-event-for-custom-control/36724924#36724924) – Arti Apr 22 '16 at 06:53
  • you can't use static events if you want to use multiple instances of this control. – Sven-Michael Stübe Apr 22 '16 at 07:03
  • added answer to your other question. – Sven-Michael Stübe Apr 22 '16 at 07:51