在Xamarin Forms上创建一个可绑定的ICommand属性

18

我有一个自定义的复选框控件,它具有我创建的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"/>
这个页面的代码背后是空的(使用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属性。我想知道我错过了什么,才能使这个命令正常工作。

编辑

我想要的是一个类似于按钮的行为的命令。

感谢大家抽出时间来!

2个回答

39

由于原来的回答现在已过时,这里是新的方法:

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

感谢您发布当前的实现。 - Dan
@MovGP0 我之前也尝试过同样的方法,但命令没有绑定。你有任何可用的示例吗? - Nuri YILMAZ
@MovGP0 这个示例会抛出以下错误: 字段初始化器不能引用非静态字段、方法或属性“MyControl.Command”。 你能帮我吗? - Hikari
2
@Hikari 在构造函数中初始化 ;) - Marc_Alx

24

这是一个类似伪代码的东西:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接