Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

mvvm

xaml

maui

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.

like image 706
eengstroem Avatar asked Jun 09 '26 14:06

eengstroem


1 Answers

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>
like image 52
Zack Avatar answered Jun 11 '26 04:06

Zack