我是Xamarin.forms的新手,我正在尝试使用我从列表中创建的多个CheckBox。
我知道在Xamarin.forms中不存在CheckBox所以我创建了一个我在Internet上创建的类来创建控件。
当我尝试创建CheckBox时,我看不到它。这是我创建CheckBox时的代码:
if (List1 != null && List1.Count > 0)
{
foreach (var c in List1)
{
CheckBox chk = new CheckBox();
chk.CheckedChanged += Chk_CheckedChanged;
chk.IsVisible = true;
chk.CheckBoxBackgroundColor = Color.Blue;
chk.TickColor = Color.Blue;
chk.WidthRequest = 12;
chk.HeightRequest = 12;
StackLayoutBody.Children.Add(chk);
}
}
这是CheckBox.cs的代码:
using System;
using Xamarin.Forms;
namespace TECAndroid.Services
{
public class CheckBox : View
{
public static readonly BindableProperty CheckedProperty =
BindableProperty.Create(nameof(Checked), typeof(bool), typeof(CheckBox), false, BindingMode.TwoWay,
propertyChanged: (bindable, oldValue, newValue) =>
{
((CheckBox)bindable).CheckedChanged?.Invoke(bindable, new CheckedChangedEventArgs((bool)newValue));
});
public static readonly BindableProperty TickColorProperty =
BindableProperty.Create(nameof(TickColor), typeof(Color), ypeof(CheckBox), Color.Default, BindingMode.TwoWay);
public static readonly BindableProperty CheckBoxBackgroundColorProperty = BindableProperty.Create(nameof(CheckBoxBackgroundColor), typeof(Color), typeof(CheckBox), Color.Default, BindingMode.TwoWay);
public EventHandler<CheckedChangedEventArgs> CheckedChanged;
public Color TickColor
{
get => (Color)GetValue(TickColorProperty);
set => SetValue(TickColorProperty, value);
}
public Color CheckBoxBackgroundColor
{
get => (Color)GetValue(CheckBoxBackgroundColorProperty);
set => SetValue(CheckBoxBackgroundColorProperty, value);
}
public bool Checked
{
get => (bool)GetValue(CheckedProperty);
set
{
if (Checked != value) SetValue(CheckedProperty, value);
}
}
}
public class CheckedChangedEventArgs : EventArgs
{
public CheckedChangedEventArgs(bool value)
{
Checked = value;
}
public bool Checked { get; }
}
}
有人可以帮我吗?!
此类不实现复选框的UI。它只是一个Xamarin.Forms类,用它来创建本机渲染器。通常我在需要Checkbox时使用Switch,但如果Switch不够好,你或者必须在每个平台上寻找本机渲染器实现,或者使用Xamarin.Forms的视图寻找跨平台实现。
而对于你的另一个问题,你想要的控制不是SwitchCell
,只是一个Switch
。如果您愿意,可以使用以下示例链接到文档:Switch Documentation。