Is it MVVM friendly to use other ViewModels as bindable properties?

95 Views Asked by At

First a little backstory: I am studying Xamarin for a month now, and I am about to start my first project.

I have a need where I have like 4 nested "generations" of a relational database, that I have to include in one View.

When I start to nest stuff, I am forced to move some Commands (ViewModel code) into the Model.

I want to avoid this at all cost, thus the question arise:

Is it MVVM friendly to use other ViewModels as bindable properties, like in the following Example?

ViewModels:

public class MainViewModel : FreshBasePageModel 
{
    public ObservableCollection<OtherViewModel> OtherCollection { get; set; }
}

public class OtherViewModel: FreshBasePageModel 
{
    public Command SomeCommand { get; set; }
}

And use it like this in the Views:

<ContentPage>
    <ListView ItemsSource={Binding OtherCollection} SelectedItem={Binding SomeCommand}>
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>

This approach seems Okay to me, but this is my first ever MVVM project, and I wonder if this is how you do stuff.

I use FreshMvvm as the backing framework, and it uses conventions for bindings, so the view is automatically bound to its namesake partner.

Also, if you'd like to look at my nested lists, see below: enter image description here

Thanks for your time,

1

There are 1 best solutions below

8
On

By default this behaviour isn't supported because a control only has a DataContext o BindableContex and this class is where the compiler look for your binding properties and commands.

In MVVM, you should only use a ViewModel for each View so your approach isn't frequent.

However I think that you could use the code that you proposed if you use the Path binding property and you have other control which its BindableContex is OtherViewModel