0
votes

In Xamarin.Forms, typically I'd write a custom renderer for buttons using a class name like "ButtonExt". Is it possible to write a custom renderer using the original name of (I guess overriding) the element, like "Button"?

Basically, I want to be able to add horizontal padding to all the buttons in my app, but without having to rename all Buttons to ButtonExt (there is no Padding property for Buttons in Xamarin.Forms). In other words I want to be able say new Button { Padding = 20 } and not have to say new ButtonExt { Padding = 20 } (project is C#, not XAML).

Normally, in the iOS project, I'd have:

[assembly: ExportRenderer(typeof(ButtonExt), typeof(ButtonExtRenderer))]
namespace StoreFulfillment.iOS
{
    public class ButtonExtRenderer : ButtonRenderer

and in the shared project, I'd have:

using MySharedProject;
using Xamarin.Forms;

namespace MySharedProject.Renderers
{
    public class ButtonExt : Button
    {
        ...

And then I'd say new ButtonExt { Padding = 20 }. But in order to be able to write new Button { Padding = 20 }, I can't write public class Button : Button...so how do I accomplish this?

1
@hvaughan3 - just expanded my question - can you address the update question? - jbyrd
Wondering if Extension Methods is the answer - docs.microsoft.com/en-us/dotnet/csharp/programming-guide/… - jbyrd

1 Answers

2
votes

Sure! Just register it to a normal Button type and make sure you call all the base methods of the ones you override so the original working also remains.

So your attribute to register the renderer would just look like this:

[assembly: ExportRenderer(typeof(Button), typeof(YourButtonRenderer))]

Also, make sure you actually need a custom renderer. If you just want to have a simple styling issue, look at the Xamarin.Forms styling possibilities and especially implicit styling.