首页 文章

在Xamarin Forms上创建ICommand Bindable属性

提问于
浏览
9

我有一个自定义复选框控件,我使用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属性按钮 . 我想知道我在这里缺少什么来使这个命令正常工作 .

EDIT

我正在寻找的是一个与Buttons具有类似功能的Command .

谢谢大家的时间!

2 回答

  • 17

    类似的东西(伪代码):

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

    由于original answer现已过时,以下是新方法:

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

相关问题