Search code examples
c#xamlmvvmmaui

Best practice for setting BindingContext for view, with multiple viewmodels?


Let's say we have a structure like this, for a page with a viewmodel attached:

Code-behind:

public partial class Page
{
    public Page(PageViewModel pageViewModel)
    {
        InitializeComponent();
        BindingContext = pageViewModel;
    }
}

Relevant part of the page:

 <Button Text="Click here" Command="{Binding ButtonClickedCommand}" />

The viewmodel, PageViewModel, has a RelayCommand with a method called "ButtonClicked".

Suppose then, that I want to add a text field, with some data from a different viewmodel, such as this XAML:

<CarouselView ItemsSource="{Binding NewList}">
<Label Text="{Binding ListItemName}" />
</CarouselView>

What is the best way to add a new viewmodel? Essentially adding multiple binding contexts.


Solution

  • A page is usually only bound to one binding context, you can set your own binding context in each child control to achieve this effect, like this:

       <Grid>
            <Grid.RowDefinitions>
              <RowDefinition Height="*" />
              <RowDefinition Height="*" />
            </Grid.RowDefinitions>
          
        <StackLayout
            Grid.Row="0"
            BindingContext="{Binding Source = {local:OneViewModel}}"/>
            <label Text="{Binding Name}"/>
        </StackLayout>
    
        <StackLayout
            Grid.Row="1"
            BindingContext="{Binding Source = {local:TwoViewModel}}">
            <label Text="{Binding Name}"/>
        </StackLayout>
    
      </Grid>