|
using System; |
|
using Xamarin.Forms; |
|
using Xamarin.Forms.Xaml; |
|
|
|
namespace Xamarin.Forms.Extensions |
|
{ |
|
// credits to: https://stackoverflow.com/a/841894/6884587 |
|
[ContentProperty("Path")] |
|
[AcceptEmptyServiceProvider] |
|
public class SwitchBindingExtension : BindableObject, IMarkupExtension<BindingBase> |
|
{ |
|
private readonly BindingMode _mode = BindingMode.Default; |
|
private BindingMode Mode => _mode; |
|
|
|
public IValueConverter Converter { get; set; } |
|
public object ConverterParameter { get; set; } |
|
public string Path { get; set; } |
|
public string StringFormat { get; set; } |
|
public object Source { get; set; } |
|
|
|
public object True |
|
{ |
|
get { return (object)this.GetValue(TrueProperty); } |
|
set { this.SetValue(TrueProperty, value); } |
|
} |
|
|
|
public static readonly BindableProperty TrueProperty = |
|
BindableProperty.Create( |
|
propertyName: nameof(True), |
|
returnType: typeof(object), |
|
declaringType: typeof(SwitchBindingExtension), |
|
defaultValue: null, |
|
defaultBindingMode: BindingMode.TwoWay |
|
); |
|
|
|
public object False |
|
{ |
|
get { return (object)this.GetValue(FalseProperty); } |
|
set { this.SetValue(FalseProperty, value); } |
|
} |
|
|
|
public static readonly BindableProperty FalseProperty = |
|
BindableProperty.Create( |
|
propertyName: nameof(False), |
|
returnType: typeof(object), |
|
declaringType: typeof(SwitchBindingExtension), |
|
defaultValue: null, |
|
defaultBindingMode: BindingMode.TwoWay |
|
); |
|
|
|
public BindingBase ProvideValue(IServiceProvider serviceProvider) |
|
{ |
|
var converter = new SwitchConverter(this, Converter); |
|
return new Binding(Path, Mode, converter, ConverterParameter, StringFormat, Source); |
|
} |
|
|
|
object IMarkupExtension.ProvideValue(IServiceProvider serviceProvider) |
|
{ |
|
return ProvideValue(serviceProvider); |
|
} |
|
|
|
private class SwitchConverter : IValueConverter |
|
{ |
|
private SwitchBindingExtension _switchExtension; |
|
private IValueConverter _decoratee; |
|
|
|
public SwitchConverter(SwitchBindingExtension switchExtension, IValueConverter decoratee) |
|
{ |
|
_switchExtension = switchExtension; |
|
_decoratee = decoratee; |
|
} |
|
|
|
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) |
|
{ |
|
bool b = System.Convert.ToBoolean(value); |
|
var switchedValue = b ? _switchExtension.True : _switchExtension.False; |
|
|
|
return _decoratee == null ? switchedValue : _decoratee.Convert(switchedValue, targetType, parameter, culture); |
|
} |
|
|
|
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) |
|
{ |
|
throw new NotImplementedException(); |
|
} |
|
} |
|
} |
|
} |