In MvvmCross, both regular binding and `DelayBind` are used to establish connections between views and view models, but they differ in when and how the bindings are applied.
Regular Binding
Regular binding in MvvmCross involves directly creating a binding set and applying it immediately. This is typically done in the view's code-behind using the `CreateBindingSet` method. The binding is established as soon as the `Apply` method is called, which means the view model's properties are linked to the view's properties at that moment. Here's an example of regular binding:
csharp
var set = this.CreateBindingSet();
set.Bind(myView)
.For(v => v.Text)
.To(vm => vm.UserName);
set.Apply();
This approach is straightforward and works well when the view and view model are fully initialized and ready for binding.
DelayBind
The `DelayBind` method, on the other hand, delays the application of the bindings until the view is fully loaded and ready. This is particularly useful in scenarios where the view's properties or layout might not be fully initialized when the binding is created. By delaying the binding, you ensure that the binding is applied only when the view is ready, reducing potential issues with null references or incorrect property values.
Here's how you might use `DelayBind`:
csharp
this.DelayBind(() =>
{
var set = this.CreateBindingSet();
set.Bind(myView)
.For(v => v.Text)
.To(vm => vm.UserName);
set.Apply();
});
In this example, the lambda expression passed to `DelayBind` is executed when the view is ready, ensuring that the binding is applied at the right time.
Key Differences
- Timing: Regular binding applies immediately, while `DelayBind` waits until the view is fully loaded.
- Purpose: Regular binding is suitable for most scenarios where the view and view model are ready for binding. `DelayBind` is useful when the view's initialization might interfere with the binding process.
- Usage: Both methods use the same binding syntax, but `DelayBind` wraps the binding creation and application in a delayed execution block.
In summary, `DelayBind` provides a way to ensure that bindings are applied at the right moment, avoiding potential issues with view initialization, while regular binding is more straightforward and suitable for simpler scenarios.
Citations:[1] https://www.mvvmcross.com/documentation/fundamentals/data-binding
[2] https://stackoverflow.com/questions/41768962/mvvmcross-default-binding-mode-used-in-a-project
[3] https://stackoverflow.com/questions/17156368/
[4] https://www.mvvmcross.com/documentation/plugins/methodbinding
[5] https://www.mvvmcross.com/documentation/advanced/customizing-using-App-and-Setup
[6] https://www.nuget.org/packages/MvvmCross/
[7] https://blog.ostebaronen.dk/2018/01/mvvmcross-binding-target.html
[8] https://leaware.com/creating-cross-platform-xamarin-applications-using-the-mvvmcross-framework/