如何在xamarin表单中创建复选框

时间:2014-12-15 03:59:31

标签: xamarin

我需要xamarin表单中的复选框控件,以及检查控件时的事件,我如何才能得到它,我正在使用开关控制,但是当IsChecked更改时它没有任何事件,我需要分组复选框,它在xamarin表单中的开关控制中是不可能的

2 个答案:

答案 0 :(得分:11)

Switch控件有一个Toggled事件,当状态发生变化时将触发该事件。

表单没有Checkbox控件,因为每个移动平台都没有底层的Checkbox控件可供映射。

XF Labs(XF的一个开源扩展程序集)确实有一个可以满足您需求的beta复选框控件。

答案 1 :(得分:0)

public class CustomCheckbox : Image
{
        private const string CheckboxUnCheckedImage = "checkbox_unchecked";
        private const string CheckboxCheckedImage = "checkbox_checked";

    public CustomCheckbox()
    {
        Source = CheckboxUnCheckedImage;
        var imageTapGesture = new TapGestureRecognizer();
        imageTapGesture.Tapped += ImageTapGestureOnTapped;
        GestureRecognizers.Add(imageTapGesture);
        PropertyChanged += OnPropertyChanged;
    }

    private void ImageTapGestureOnTapped(object sender, EventArgs eventArgs)
    {
        if (IsEnabled)
        {
            Checked = !Checked;
        }
    }

    /// <summary>
    /// The checked changed event.
    /// </summary>
    public event EventHandler<bool> CheckedChanged;

    /// <summary>
    /// The checked state property.
    /// </summary>
    public static readonly BindableProperty CheckedProperty = BindableProperty.Create("Checked", typeof(bool), typeof(CustomCheckbox), false, BindingMode.TwoWay, propertyChanged: OnCheckedPropertyChanged);

    public bool Checked
    {
        get
        {
            return (bool)GetValue(CheckedProperty);
        }

        set
        {
            if (Checked != value)
            {
                SetValue(CheckedProperty, value);
                CheckedChanged?.Invoke(this, value);
            }
        }
    }

    private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e?.PropertyName == IsEnabledProperty.PropertyName)
        {
            Opacity = IsEnabled ? 1 : 0.5;
        }
    }

    private static void OnCheckedPropertyChanged(BindableObject bindable, object oldValue, object newValue)
    {
        var checkBox = bindable as CustomCheckbox;
        if (checkBox != null)
        {
            var value = newValue as bool?;
            checkBox.Checked = value.GetValueOrDefault();
            checkBox.Source = value.GetValueOrDefault() ? CheckboxCheckedImage : CheckboxUnCheckedImage;
        }
    }
}