Create an ICommand Bindable property on Xamarin Forms

前端 未结 2 1056
滥情空心
滥情空心 2021-02-13 16:13

I have a custom checkbox control that I created with an ICommand property and the corresponding bindable property (my checkbox is a Xamarin.Forms XAML Page), the code is:

<
相关标签:
2条回答
  • 2021-02-13 16:47

    Since the original answer is now obsolete, here is the new method:

    using System.Windows.Input;
    
    public partial class MyControlExample : ContentView
    {
        // BindableProperty implementation
        public static readonly BindableProperty CommandProperty = 
            BindableProperty.Create(nameof(Command), typeof(ICommand), typeof(MyControlExample), null);
    
        public ICommand Command
        {
            get { return (ICommand)GetValue(CommandProperty); }
            set { SetValue(CommandProperty, value); }
        }
    
        // Helper method for invoking commands safely
        public static void Execute(ICommand command)
        {
            if (command == null) return;
            if (command.CanExecute(null))
            {
                command.Execute(null);
            }
        }
    
        public MyControlExample()
        {
            InitializeComponent();
        }
    
        // this is the command that gets bound by the control in the view
        // (ie. a Button, TapRecognizer, or MR.Gestures)
        public Command OnTap => new Command(() => Execute(Command));
    }
    
    0 讨论(0)
  • 2021-02-13 16:52

    Something like that (pseudocode):

    public class YourClassName : View
    {
        public YourClassName()
        {
            var gestureRecognizer = new TapGestureRecognizer();
    
            gestureRecognizer.Tapped += (s, e) => {
                if (Command != null && Command.CanExecute(null)) {
                    Command.Execute(null);
                }
            };
    
            var label = new Label();
            label.GestureRecognizers.Add(gestureRecognizer);
        }
    
        public static readonly BindableProperty CommandProperty =
        BindableProperty.Create<YourClassName, ICommand>(x => x.Command, null);
    
        public ICommand Command
        {
            get { return (ICommand)GetValue(CommandProperty); }
            set { SetValue(CommandProperty, value); }
        }
    }
    
    0 讨论(0)
提交回复
热议问题