A BindableProperty is .NET MAUI metadata that backs a regular property and gives it binding support. A binding target must inherit BindableObject and expose a bindable property; a binding source, such as a ViewModel property, can remain a regular property. This lets a custom control present a simple public value while hiding its internal controls and code-behind state. section 11.2
Use a bindable property when a custom control needs to participate in XAML binding just like built-in controls. For example, a custom stepper can expose Value externally and bind it to Count, even though its buttons and entry manage the value internally. section 11.2 section 11.2.1
Create a bindable property by following the control convention:
- Declare a public static readonly BindableProperty whose name is the backed property name plus Property, such as ValueProperty. section 11.2.1
- Call BindableProperty.Create with the backed property name, its type, and the declaring custom-control type. section 11.2.1
- Implement the regular property's getter with GetValue and its setter with SetValue. Cast GetValue's object result to the property's type. section 11.2.1
- Supply a default value when the binding or a trigger must revert to an enabled initial state, and use a propertyChanged delegate when child controls must reflect a changed value. section 11.2.2
Expose a bindable Value
A custom stepper declares ValueProperty for an int and wraps it with a Value property. Once wrapped, the control can be used in XAML with Value bound to Count. The control can then both display changes from its binding context and provide its value through the same public property. section 11.2.1
Listing 11.4 The BindableProperty and updated property
public static readonly BindableProperty ValueProperty = BindableProperty.Create(
nameof(Value),
typeof(int),
typeof(MildredStepper));
public int Value
{
get => (int)GetValue(ValueProperty); #1
set => SetValue(ValueProperty, value); #2
}
This listing shows the paired pieces: the static ValueProperty metadata and the ordinary Value wrapper that delegates reads and writes to GetValue and SetValue. section 11.2.1
A bindable property can also preserve familiar control APIs. A custom control based on ContentView can expose IsEnabled for a DataTrigger, give it a true default, and propagate changes to its entry and plus/minus buttons through a property-changed callback. section 11.2.2
