-
Couldn't load subscription status.
- Fork 2
behaviors
Behaviors are used to add additional functionality to a control without having to subclass them. With Shield MVVM, they take a similar approach to the way BindbaleProperties work, so developers can chain the behaviors with the BindingHelper. They are also defined as extension methods, similar to the way Converters are defined. The biggest difference is that Behaviors may need specific event handlers, so developers will have to specify the generic parameters directly.
To define a new Behavior, the control type and the handler must be defined. Here is an example extension method:
namespace CoreBTS.Maui.ShieldMVVM.Behaviors;
public static partial class Behaviors
{
public static Behavior<Entry> ApplyColorForValue(this BindingBehavior<Entry> _,
Color colorToChangeTo,
Color defaultColor,
Func<string, bool>? mustApplyColorCallback = null) =>
Create<Entry, EventHandler<TextChangedEventArgs>>(_,
c => (sender, e) => c.TextColor = (mustApplyColorCallback ??= val => !string.IsNullOrEmpty(val))(c.Text) ? colorToChangeTo : defaultColor,
(c, e) => c.TextChanged += e,
(c, e) => c.TextChanged -= e);
}Like Converters, any number of typed parameters can be sent in. Here, whenever the TextChanged event fires, the control's TextColor will change according to a callback that determines which color to apply. This is what the code would look like if the color should change when the length of the text is more than 2 characters long:
Binder.WithControl(Counter)
.Behavior(c => c.ApplyColorForValue(Colors.Red, Colors.Black, val => val?.Length > 2))
.For(c => c.BindText(), vm => vm.Counter, c => c.ConvertToString());These behavior methods can add great flexibility to all controls throughout an application. Also like Converters, Intellisense will only show the behaviors that are available for the specific control type being bound, and a similar overload that takes a View Model is also available:
Binder.WithControl(Counter)
.Behavior((c, vm) => c.ApplyColorForValue(vm.MyColor, Colors.Black, val => val?.Length > 2))
.For(c => c.BindText(), vm => vm.Counter, c => c.ConvertToString());