Adam
Adam

Reputation: 4780

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 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.

Upvotes: 2

Views: 3490

Answers (2)

Alexander
Alexander

Reputation: 614

Late answer but maybe for the future: You can raise the click event of a button from outside using the IButtonController interface.

The Xamarin.Forms.Button class implements this interface which provides one single method: SendClicked

By casting your Xamarin.Forms element in the renderer (this.Element) to IButtonController you're able to call this method and raise the clicked event of the Xamarin.Forms.Button.

I also created a blog post about this topic: http://software.fauland.cc/?p=5637

Upvotes: 1

shf301
shf301

Reputation: 31404

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();

Upvotes: 3

Related Questions