Xamarin.Forms Content of a button

后端 未结 6 1046
我寻月下人不归
我寻月下人不归 2021-02-15 16:13

I\'m trying to add a custom content to a button in Xamarin Forms.

By default Button is created like this:

6条回答
  •  暖寄归人
    2021-02-15 16:54

    Thanks Tomasz, good inspiration. However for me, your control didn´t pick up the tap-event on all platforms and used obsolete Xamarin.Forms methods "BindableProperty.Create<" and . So I came up with this one.

    Here it is:

    public class ContentButton:ContentView
    {
        private readonly TapGestureRecognizer _tapGestureRecognizer;
    
        public ContentButton()
        {
            _tapGestureRecognizer = new TapGestureRecognizer();
            GestureRecognizers.Add(_tapGestureRecognizer);          
        }
    
        protected override void OnChildAdded(Element child)
        {
            base.OnChildAdded(child);
            if (child is View childview)
            {
                childview.GestureRecognizers.Add(_tapGestureRecognizer);
            }
        }
    
        public static readonly BindableProperty CommandProperty = BindableProperty.Create(nameof(Command), typeof(ICommand),
            typeof(ContentButton), null, BindingMode.Default, null, CommandPropertyChanged);
    
        private static void CommandPropertyChanged(BindableObject bindable, object oldValue, object newValue)
        {
            if (newValue is ICommand command && bindable is ContentButton contentButton)
            {
                contentButton._tapGestureRecognizer.Command = command;              
            }
        }
    
        public ICommand Command
        {
            get => (ICommand)GetValue(CommandProperty);
            set => SetValue(CommandProperty, value);
        }
    }
    

提交回复
热议问题