Rolf
Rolf

Reputation: 301

Where to instantiate the viewmodel of a .NET MAUI ContentView with bindable properties?

I've a ContentView in .NET MAUI with two bindable properties: ListData and ListType. ListData is of type string and contains a serialized JSON object. ListType is a string whose value controls the appearance of the list. The ContentView itself consists mainly of a CollectionView and I'm using the MVVM Community Toolkit.

My question:

Where to create an instance of the viewmodel with the values of the bindable properties and assign it to the BindingContext? The values of the bindable properties are not yet present in the constructor of the ContentView.

Upvotes: 0

Views: 642

Answers (1)

H.A.H.
H.A.H.

Reputation: 3887

Where to create an instance of the viewmodel

The answer is you simply don't.

Using dependency injection is what people do those days. In fact - by creating new project in MAUI you are already using it.

Instances are created when and if they are needed. You just set the rules for it.

...and assign it to the BindingContext

This is usually done in the constructor.

Anyway, I see what you are trying to do, and I do not think that this is the right approach for it.

I would either use a Converter, or Template Selector (or something similar).

https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/datatemplate

Upvotes: 0

Related Questions