1. 程式人生 > >Xamarin.Forms中實現CheckBox控件

Xamarin.Forms中實現CheckBox控件

model != forms body ble 圖片 data- () enabled

Xamarin.Forms中實現CheckBox控件

由於Xamarin.Forms中沒有Checkbox這個基礎控件,我們就只能自己來實現啦!

這裏采用的是繼承Image來實現Checkbox控件,代碼如下所示:

IconUnChecked :未選中狀態的圖片名稱

IconChecked:選中狀態的圖片名稱

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using Xamarin.Forms;

namespace AppTest.CustomView
{
    
public class Checkbox : Image { private const string CheckboxUnCheckedImage = "IconUnChecked"; private const string CheckboxCheckedImage = "IconChecked"; public Checkbox() { 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(Checkbox), 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 Checkbox; if (checkBox != null) { var value = newValue as bool?; checkBox.Checked = value.GetValueOrDefault(); checkBox.Source = value.GetValueOrDefault() ? CheckboxCheckedImage : CheckboxUnCheckedImage; } } } }

Xamarin.Forms中實現CheckBox控件