-
Couldn't load subscription status.
- Fork 2
converters
MAUI Converters aren't type-safe, take only one object parameter for extra input, and developers have to create a new class each time to define one for XAML bindings. Shield MVVM has its own IValueConverter that is type-safe and then uses generic extension methods to force the type-safety and Intellisense support on BindingHelper. In addition, a GenericConverter class was created that takes callback functions that do the conversions. With this approach, developers can create simple extension methods that handle the code without the need to create tons of converter classes. These extension methods can any number of parameters that are also fully typed and named. Here is an example of how to create one:
using System.Globalization;
namespace CoreBTS.Maui.ShieldMVVM.Converters;
public static partial class Converter
{
public static IValueConverter<int, string> ConvertToString(this BindingConverter<int, string> _,
NumberStyles style = NumberStyles.Any,
IFormatProvider? formatProvider = null) =>
Create(_,
value => value.ToString(formatProvider),
value => int.TryParse(value, style, formatProvider, out var val) ? val : default);
}If a developer was trying to set an int View Model property to a string Bind method, this ConvertToString() would show up in the Intellisense. It can take any number of typed parameters that can be used by the callback methods below. This makes adding new converters very easy. If a converter is more of a one time use, then a new GenericConverter could also be created and used directly if need be. That could would look something like this:
Binder.WithControl(Counter)
.For(c => c.BindText(), vm => vm.Counter,
c => GenericConverter<int, string>.Create(value => (value + 1).ToString()));The ConvertBack method is optional, but if the bindable property is two-way, then the code will most likely crash at run-time.