Xamarin Forms: How can I add padding to a button?

前端 未结 6 1051
天涯浪人
天涯浪人 2021-02-01 19:30

I have the following XAML Xamarin.Forms.Button

I tried to add

6条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-01 20:06

    usage:

    
    

    advantages:

    • no nasty sideeffects
    • no problem with alignments
    • no viewtree uglyness
    • no view depth incrementation

    ios:

    [assembly: ExportRenderer(typeof(EnhancedButton), typeof(EnhancedButtonRenderer))]
    namespace YOURNAMESPACE.iOS
    {
        public class EnhancedButtonRenderer : ButtonRenderer
        {
            protected override void OnElementChanged(ElementChangedEventArgs

    android:

    [assembly: ExportRenderer(typeof(EnhancedButton), typeof(EnhancedButtonRenderer))]
    namespace YOURNAMESPACE.Droid
    {
        public class EnhancedButtonRenderer : ButtonRenderer
        {
            protected override void OnElementChanged(ElementChangedEventArgs

    pcl:

    public class EnhancedButton : Button
    {
        #region Padding    
    
        public static BindableProperty PaddingProperty = BindableProperty.Create(nameof(Padding), typeof(Thickness), typeof(EnhancedButton), default(Thickness), defaultBindingMode:BindingMode.OneWay);
    
        public Thickness Padding
        {
            get { return (Thickness) GetValue(PaddingProperty); }
            set { SetValue(PaddingProperty, value); }
        }
    
        #endregion Padding
    }
    

    Solution using effects instead of renderers, to allow easy usage for more than one control:

    XAML:

    
    

    PCL:

    [assembly: ResolutionGroupName("ComponentName")]
    namespace XamTest
    {
        public class PaddingEffect : RoutingEffect
        {
            /// 
            protected PaddingEffect(string effectId) : base($"ComponentName.{nameof(PaddingEffect)}")
            {
            }
    
            public Thickness Padding { get; set; }
        }
    }
    

    Android:

    [assembly: ResolutionGroupName("ComponentName")]
    [assembly: ExportEffect(typeof(XamTest.Droid.PaddingEffect), "PaddingEffect")]
    namespace XamTest.Droid
    {
        public class PaddingEffect : PlatformEffect
        {
            /// 
            protected override void OnAttached()
            {
                if (this.Control != null)
                {
                    var firstMatch = this.Element.Effects.FirstOrDefault(d => d is XamTest.PaddingEffect);
                    if (firstMatch is XamTest.PaddingEffect effect)
                    {
                        this.Control.SetPadding((int)effect.Padding.Left, (int)effect.Padding.Top, (int)effect.Padding.Right, (int)effect.Padding.Bottom);
                    }
                }
            }
    
            /// 
            protected override void OnDetached()
            {
            }
        }
    }
    

提交回复
热议问题