简体   繁体   中英

Xamarin Form: Button inside Grid have a margin. How to remove that margin

I have a grid contains a set of button. I have set the columnSpacing of the grid to 0 but still have the margin between buttons. I assumed its the button control. Even if I put the margin on button to 0, the result is the same.

I can't use boxView, i need a text and clickable on it.

Old thread, but I was getting this on my Android platform. Upgrading Xamarin.Forms from 2.5 to recently released 3.1 seems to have resolved it.

The problem is, android button has default background drawable that has margin. You can remove it using custom renderer. Xamarin.Forms custom renderer

Example:

using System;
using test.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(Button), typeof(DefaultButtonRenderer))]
namespace test.Droid
{
    public class DefaultButtonRenderer: ButtonRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
        {
            base.OnElementChanged(e);

            // Control is Android.Widget.Button, Element is Xamarin.Forms.Button
            if (Control != null && Element != null)
            {
                // remove default background image
                Control.Background = null;

                // set background color
                Control.SetBackgroundColor(Element.BackgroundColor.ToAndroid());
            }
        }

        protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);

            if (e.PropertyName == "BackgroundColor")
            {
                // You have to set background color here again, because the background color can be changed later.
                Control.SetBackgroundColor(Element.BackgroundColor.ToAndroid());
            }
        }
    }
}

This code will remove button click effect. If you want to remain the effect, you have to set Control.Background to proper resource. (ex: Android.Resource.Attribute.SelectableItemBackground)

Alternatively, you can use label with TapGestureRecognizer . You can add TapGestureRecognizer to any view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM