Xamarin Converters normally have to be static (not changed after start) and classes which makes them quite an overkill for what they do in the most cases. Therefore I thought it would be easier to define them in a one-liner at runtime.
CodePudding user response:
Yes it is possible with an wrapper class and if you create your objects before calling InitializeComponent
.
Here is an example wrapper class:
public class XamarinFormsConverter<TIn, TOut> : IValueConverter {
private readonly Func<TIn, TOut> _func;
public XamarinFormsConverter(Func<TIn, TOut> func) => _func = func;
public object Convert(object value, Type targetType, object _, CultureInfo __) {
if (targetType != typeof (TOut)) {
throw new Exception("Converter used with wrong targetType");
}
if (value is TIn val) {
return _func(val);
}
throw new Exception("Converter used with wrong inputType");
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotImplementedException();
}
and an example on how to use it:
public ResourceDictionary Converters { get; } = new ResourceDictionary {
["IsLoggedInToColor"] = new XamarinFormsConverter<bool, Color>(input => input ? Color.FromRgb(132, 255, 255) : Color.FromRgb(64, 196, 255)),
["IsLoggedInToView"] = new XamarinFormsConverter<bool, object>(input => input ? Views.User.ToString() : Views.Login.ToString()),
["BoolInvert"] = new XamarinFormsConverter<bool, bool>(input => !input),
["FromPercent"] = new XamarinFormsConverter<int, double>(input => (double)input / 100)
};
its important to add the Converters befor initalizing:
public MainPage() {
ViewModel = new ViewModel();
Resources.Add(ViewModel.Converters);
InitializeComponent();
BindingContext = ViewModel;
}
Technicallly it would also be possible to change the behaviors of the converters after the initialization, but the names and objects must be created before.
I hope some people can use this to make their code simpler and more readable.