Create an ICommand Bindable property on Xamarin Forms

前端 未结 2 1057
滥情空心
滥情空心 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));
    }
    

提交回复
热议问题