16

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

复选框.xaml

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

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

<TapGestureRecognizer Tapped="OnCheckBoxTapped"/>

复选框.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"/>

此页面的代码后面是空的(带有 InitializeComponent() 的构造函数)。我也有这个页面的 ViewModel 和这个代码:

条款和条件ViewModel.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 属性按钮。我想知道我在这里缺少什么以使该命令正常工作。

编辑

我正在寻找的是一个行为类似于按钮的命令。

谢谢大家的时间!

4

2 回答 2

33

由于原始答案现已过时,因此这是新方法:

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));
}
于 2016-12-30T06:06:11.330 回答
22

类似的东西(伪代码):

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); }
    }
}
于 2015-07-31T14:31:34.093 回答