我有以下Xamarin形式的自定义开关,它基本上只是在更改我的Switch
的颜色:
public class CustomSwitch : Switch
{
public static readonly BindableProperty SwitchOnColorProperty = BindableProperty.Create(nameof(SwitchOnColor), typeof(Color), typeof(ExtSwitch), Color.Default);
public static readonly BindableProperty SwitchOffColorProperty = BindableProperty.Create(nameof(SwitchOffColor), typeof(Color), typeof(ExtSwitch), Color.Default);
public static readonly BindableProperty SwitchThumbColorProperty = BindableProperty.Create(nameof(SwitchThumbColor), typeof(Color), typeof(ExtSwitch), Color.Default);
public Color SwitchOffColor { get => (Color)GetValue(SwitchOffColorProperty); set => SetValue(SwitchOffColorProperty, value); }
public Color SwitchOnColor { get => (Color)GetValue(SwitchOnColorProperty); set => SetValue(SwitchOnColorProperty, value); }
public Color SwitchThumbColor { get => (Color)GetValue(SwitchThumbColorProperty); set => SetValue(SwitchThumbColorProperty, value); }
}
然后我在XAML中使用它,如下所示:
<local:CustomSwitch SwitchThumbColor="White" SwitchOnColor="Red" SwitchOffColor="Gray" IsToggled="{Binding IsToggled, Source={x:Reference this}}" >
<local:CustomSwitch.Behaviors>
<b:EventHandlerBehavior EventName="Toggled">
<b:InvokeCommandAction Command="{Binding ToggledCommand, Source={x:Reference this}}"
CommandParameter="{Binding ., Source={x:Reference this}}" />
</b:EventHandlerBehavior>
</local:CustomSwitch.Behaviors>
</local:CustomSwitch>
在我的iOS中:
protected override void OnElementChanged(ElementChangedEventArgs<Switch> e)
{
base.OnElementChanged(e);
if (e.OldElement != null || e.NewElement == null) return;
CustomSwitch s = Element as CustomSwitch;
this.Control.OnTintColor = s.SwitchOnColor.ToUIColor();
}
在Android中:
CustomSwitch s;
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Switch> e)
{
base.OnElementChanged(e);
if (e.OldElement != null || e.NewElement == null)
return;
s = (CustomSwitch)Element;
if (Control != null)
{
SwitchColorChange();
Control.CheckedChange += OnCheckedChange;
}
}
void OnCheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e)
{
SwitchColorChange();
}
void SwitchColorChange()
{
if (Control.Checked)
{
Control.TrackDrawable.SetColorFilter(s.SwitchOnColor.ToAndroid(), PorterDuff.Mode.SrcAtop);
Control.ThumbDrawable.SetColorFilter(s.SwitchOnColor.ToAndroid(), PorterDuff.Mode.SrcAtop);
}
else
{
Control.TrackDrawable.SetColorFilter(s.SwitchOffColor.ToAndroid(), PorterDuff.Mode.SrcAtop);
Control.ThumbDrawable.SetColorFilter(s.SwitchOffColor.ToAndroid(), PorterDuff.Mode.SrcAtop);
}
}
两个渲染器在更改Switch
的颜色时都能完美工作,但是在Android
中,它以某种方式使命令无法正常工作。它不再触发命令,因此不保存切换选择。
有人知道我在这里想念什么吗?