在 Xamarin Forms 上创建一个 ICommand Bindable 属性

Create an ICommand Bindable property on Xamarin Forms

我有一个使用 ICommand 属性 和相应的可绑定 属性 创建的自定义复选框控件(我的复选框是一个 Xamarin.Forms XAML 页面),代码是:

CheckBox.xaml

<Image x:Name="imgCheckBox"
       WidthRequest="20"
       HeightRequest="20"/>

<Label x:Name="lblCheckBox"
       TextColor="Black"
       VerticalOptions="CenterAndExpand"/>

<TapGestureRecognizer Tapped="OnCheckBoxTapped"/>

CheckBox.xaml.cs

public partial class CheckBox : ContentView
{
    private static ImageSource uncheckedImage;
    private static ImageSource checkedImage;

    public CheckBox()
    {
        InitializeComponent();
        uncheckedImage = ImageSource.FromResource("cbUnchecked.png");
        checkedImage = ImageSource.FromResource("cbChecked.png");
        imgCheckBox.Source = uncheckedImage;
    }

    public static readonly BindableProperty IsCheckedProperty =
        BindableProperty.Create<CheckBox, bool>(
            checkbox => 
                checkbox.IsChecked,
                false,
                propertyChanged: (bindable, oldValue, newValue) =>
                {
                    CheckBox checkbox = (CheckBox)bindable;
                    EventHandler<bool> eventHandler = checkbox.CheckedChanged;
                    if (eventHandler != null)
                    {
                        eventHandler(checkbox, newValue);
                    }
                });        

    public bool IsChecked
    {
        set { SetValue(IsCheckedProperty, value); }
        get { return (bool)GetValue(IsCheckedProperty); }
    }

    void OnCheckBoxTapped(object sender, EventArgs args)
    {
        IsChecked = !IsChecked;
        if (IsChecked)
        {
            imgCheckBox.Source = checkedImage;
        }
        else
        {
            imgCheckBox.Source = uncheckedImage;
        }
    }

    public static readonly BindableProperty CheckBoxCommandProperty =
        BindableProperty.Create<CheckBox, ICommand>(
        checkbox =>
            checkbox.CheckBoxCommand,
            null,
            BindingMode.TwoWay,
            propertyChanged: (bindable, oldValue, newValue) =>
            {
                CheckBox checkbox = (CheckBox)bindable;
                EventHandler<bool> eventHandler = checkbox.CheckedChanged;
                if (eventHandler != null)
                {
                    eventHandler(checkbox, checkbox.IsChecked);
                }
            });

    public event EventHandler<bool> CheckedChanged;

    public ICommand CheckBoxCommand
    {
        get { return (ICommand)GetValue(CheckBoxCommandProperty); }
        set { SetValue(CheckBoxCommandProperty, value); }
    }
}

此复选框实现在另一个名为 TermsAndConditionsPage 的页面上,该页面也是一个 Xamarin.Forms XAML 页面,实现代码为:

<toolkit:CheckBox Text="{Binding txtCheckBox}"
                  FontSize="Small"
                  CheckBoxCommand="{Binding OnCheckBoxTapChanged}"
                  IsChecked="{Binding IsCheckedChanged, Mode=TwoWay}"/>

      <Button Text="Next"
              Command="{Binding Next_OnClick}"
              IsEnabled="{Binding Next_IsEnabled}"
              HorizontalOptions="CenterAndExpand"
              Clicked="OnNextClicked"/>

此页面的代码隐藏是空的(Constructur with InitializeComponent())。 我也有此页面的 ViewModel,代码如下:

TermsAndConditionsViewModel.cs

private string _txtCheckBox;
public string txtCheckBox
{ get { return _txtCheckBox; }
    set 
    { 
        _txtCheckBox = value;
        OnPropertyChanged("txtCheckBox");
    }
}

private bool _Next_IsEnabled;
public bool Next_IsEnabled
{
    get { return _Next_IsEnabled; }
    set
    {
        _Next_IsEnabled = value;
        OnPropertyChanged("Next_IsEnabled");
    }
}

private bool _IsCheckedChanged;
public bool IsCheckedChanged
{
    get { return _IsCheckedChanged; }
    set 
    { 
        _IsCheckedChanged = value;
        OnPropertyChanged("IsCheckedChanged");
    }
}

public ICommand Next_OnClick { get; set; }
public ICommand OnCheckBoxTapChanged { get; set; }

public TermsAndConditionsViewModel()
{
    txtCheckBox = "I agree with the terms and conditions";
    Next_OnClick = new Command(NextClicked);
    OnCheckBoxTapChanged = new Command(CheckBoxTapped);
}

private void CheckBoxTapped()
{
    if (IsCheckedChanged)
    { Next_IsEnabled = true; }
    else
    { Next_IsEnabled = false; }
}

private void NextClicked()
{ App.Current.MainPage = new Views.HelloWorld(); }

#region INPC
public void OnPropertyChanged(string propertyName)
{
    if (PropertyChanged != null)
    { PropertyChanged(this, new PropertyChangedEventArgs(propertyName));          }                
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion  

现在,提问时间:我遇到的问题是 CheckBoxTapped 命令不起作用,我的意思是,它没有任何作用,虽然每次我触摸它时复选框图像都会改变,但它不会改变我按钮的 Next_IsEnabled 属性 。我想知道我在这里缺少什么才能使此命令正常工作。

编辑

我正在寻找的是一个与按钮具有的命令类似的命令。

感谢大家的宝贵时间!

类似的东西(伪代码):

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); }
    }
}

由于 现已过时,这里是新方法:

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));
}