Raise the Xamarin.Forms-Button clicked event in a renderer.
durch Alexander Fauland
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.
Recommended Posts
Serialize an Entity Framework entity to JSON (Newtonsoft.Json)
02 Feb 2017 - Backend & Datenbanken, C# .NET, Entity Framework
Xamarin.Forms Gesture-Pattern-Login
26 Sep 2016 - C# .NET, Visual Studio, Xamarin