Search code examples
c#xamarinicommandeventhandlerxamarin.forms

Xamarin Forms Event Bubbling and Invoking Operations on a Custom Renderer


I am creating a custom Xamarin Forms control that contains three buttons (1,2,3) inside a view. Let's just call it a GaugeView for the sake of this example. Here is how it is currently setup:

  • The GuageView has a custom renderer on both iOS and Android called GuageViewRenderer.
  • The GuageView exposes event handlers for Clicked1, Clicked2, and Clicked3.
  • The GuageView exposes ICommand properties for Click1, Click2, and Click3.

The problem is, I need to fire the event handlers from the custom renderer because only the native platform control knows when one of the buttons has been pressed. How do you bubble the events back up to the GuageView, which is where the shared code lives?

I was planning to wire up the commands and the event handlers down inside the custom renderer, but I'm having a heck of a time with it since events can only be fired from within the original class (GuageView).

Is there a better way to structure this? The main thing I am trying to do is expose the platform native guage and wire its buttons up so the event handlers in the shared code (GuageView) gets the event firings.


Solution

  • Right, you can't raise events outside of the class that declares them. So you'll have to add a method to GaugeView that will raise the events. I would also have that same method invoke the commands as well. So in GaugeView

    public void RaiseClick1() {
        var clicked1 = Clicked1;
        if (clicked1 != null)
            clicked1(this, EventArgs.Empty);
    
        if (Command1 != null && Command1.CanExecute(Command1Paramter))
             Command1.Execute(Command1Parameter);
    }
    

    Then in GaugeViewRender whenever you need to notify the view that a button was clicked:

    Element.RaiseClick1();