Raise the Xamarin.Forms-Button clicked event in a renderer.

I just wrote a renderer to use a Hyperlink-Button in my Xamarin.Forms application. Since the default representation of a button on iOS uses a hyperlink style there’s no need to create an iOS renderer. So here’s my UWP renderer:

[assembly: ExportRenderer(typeof(LinkButton), typeof(LinkButtonRenderer))]
namespace InventoryCatalogApp.Windows10.Renderers
{
    public class LinkButtonRenderer : ViewRenderer<LinkButton, HyperlinkButton>
    {
        #region Overrides of ViewRenderer<LinkButton,HyperlinkButton>

        protected override void OnElementChanged(ElementChangedEventArgs<LinkButton> e)
        {
            base.OnElementChanged(e);

            if (Control == null)
            {
                SetNativeControl(new HyperlinkButton());
            }

            Control.Background = new SolidColorBrush(Colors.Transparent);
            Control.Content = this.Element.Text;
            Control.Click += (sender, args) =>
            {
                var bc = (IButtonController)this.Element;
                bc.SendClicked();
            };
        }

        #endregion
    }
}

 

The LinkButton class is defined in the portable lib and is an empty derivation from Xamarin.Forms.Button. Since you cannot raise an event from outside a class I was not able to raise the Xamarin.Forms.Button.Clicked event in my renderer. So I started investigating the Xamarin.Forms.Button class and found the IButtonController interface. This interface provides a single method: void SendClicked();

So here we go. I only had to cast my LinkButton (this.Element in the renderer) to IButtonController and call the SendClicked method. Easy going – thanks to my Reflector-Tool.

Note: There’s no request for an Android version of the APP by the customer so I didn’t implement a solution for Android. But raising the click-event works platform independent.

Share

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*