How can I associate multiple viewmodels to a single form?

Hello,

in a form I have objects that are populated by a db query and a combobox that is populated manually.

The codes of both cases are in two different viewmodels.

Is it possible to associate multiple viewmodels that take data from different sources in a single form?


C# CODE VIEWMODEL


class ContactViewModel

    {

        public string Supporto { get; set; }

        public string EmailSupp { get; set; }

        public string TelefonoSupp { get; set; }

        public string ImageSupp { get; set; }

        public string Commerciale { get; set; }

        public string EmailComm { get; set; }

        public string TelefonoComm { get; set; }

        public string ImageComm { get; set; }


        public ContactViewModel()

        {

            try

            {

                using (var connection = new SqlConnection(Connessione.Path))

                {

                    connection.Open();

                    var command = connection.CreateCommand();

                    command.CommandText = "SELECT Id, Tipologia, Email, Telefono1, ISNULL(Telefono2,'') FROM Ruoli Where Id in (2,3) ORDER BY id";


                    using (var reader = command.ExecuteReader())

                    {

                        while (reader.Read())


                        {


                            switch (reader.GetInt32(0))

                            {

                                case 2:

                                    Supporto = reader.GetString(1);

                                    EmailSupp = reader.GetString(2);

                                    TelefonoSupp = reader.GetString(3);

                                    ImageSupp = "support.png";

                                    break;

                                case 3:

                                    Commerciale = reader.GetString(1);

                                    EmailComm = reader.GetString(2);

                                    TelefonoComm = reader.GetString(3);

                                    ImageComm = "money.png";

                                    break;

                            }


                        }

                        connection.Close();

                        return;

                    }

                }


            }

            catch (Exception)

            {

                Supporto = "Dato non disponibile";

                Commerciale = "Dato non disponibile";

            }


        }



    }


    class TipologieViewModel

    {


        public ObservableCollection<TicketTipologie> TicketTipologies { get; set; }

        public TipologieViewModel()

        {

            TicketTipologies = new ObservableCollection<TicketTipologie>();

            TicketTipologies.Add(new TicketTipologie() { Id = 1, Tipologia = "Assistenza tecnica" });

            TicketTipologies.Add(new TicketTipologie() { Id = 2, Tipologia = "Nuova password" });

            TicketTipologies.Add(new TicketTipologie() { Id = 3, Tipologia = "Aggiornamento dati" });

            TicketTipologies.Add(new TicketTipologie() { Id = 4, Tipologia = "Info commerciale" });


        }


    }


C# CODE PAGE


namespace Test

{

    [XamlCompilation(XamlCompilationOptions.Compile)]

    public partial class Contact : ContentPage

    {


        public Contact()

        {

            InitializeComponent();

            BindingContext = new ContactViewModel();

        }


        private async void Button_Clicked(object sender, EventArgs e)

        {


        }


        private void SfButton_Clicked(object sender, EventArgs e)

        {


        }


        private void ComboBox_SelectionChanged(object sender, Syncfusion.XForms.ComboBox.SelectionChangedEventArgs e)

        {


        }

    }

}



XAML CODE


<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"

             xmlns:button="clr-namespace:Syncfusion.XForms.Buttons;assembly=Syncfusion.Buttons.XForms"

             xmlns:inputLayout="clr-namespace:Syncfusion.XForms.TextInputLayout;assembly=Syncfusion.Core.XForms"

             xmlns:gradient="clr-namespace:Syncfusion.XForms.Graphics;assembly=Syncfusion.Core.XForms"

             xmlns:comboBox="clr-namespace:Syncfusion.XForms.ComboBox;assembly=Syncfusion.SfComboBox.XForms"

             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"

             xmlns:ListCollection="clr-namespace:System.Collections.Generic;assembly=netstandard"

             x:Class="Test.Contact"

             BackgroundColor="#f1e9dc">

    <StackLayout>

        <StackLayout HorizontalOptions="FillAndExpand">

            <!-- header -->

            <StackLayout BackgroundColor="#a72321" Orientation="Vertical" VerticalOptions="StartAndExpand" HorizontalOptions="FillAndExpand">

                <StackLayout.HeightRequest>

                    <OnPlatform x:TypeArguments="x:Double" iOS="64" Android="50" />

                </StackLayout.HeightRequest>

                <StackLayout.MinimumHeightRequest>

                    <OnPlatform x:TypeArguments="x:Double" iOS="64" Android="50" />

                </StackLayout.MinimumHeightRequest>

                <StackLayout Orientation="Horizontal" VerticalOptions="FillAndExpand" HorizontalOptions="CenterAndExpand" Padding="3,0,0,0">

                    <Label Text="CONTACT"

                       FontSize="14"

                       FontAttributes="Bold"

                       TextColor="white"

                       BackgroundColor="Transparent"

                       HorizontalOptions="StartAndExpand"

                       VerticalOptions="FillAndExpand"

                       VerticalTextAlignment="Center"

                       HorizontalTextAlignment="Start"/>

                </StackLayout>

            </StackLayout>

        </StackLayout>

        <Grid Margin="5">

            <Grid.RowDefinitions>

                <RowDefinition Height="Auto"/>

                <RowDefinition Height="Auto"/>

                <RowDefinition Height="Auto"/>

                <RowDefinition Height="5*"/>

            </Grid.RowDefinitions>

            <Grid Grid.Row="0" Padding="0,0,0,10">

                <Grid>

                    <Grid.RowDefinitions>

                        <RowDefinition Height="Auto"/>

                        <RowDefinition Height="Auto"/>

                    </Grid.RowDefinitions>

                    <StackLayout Grid.Row="0" Orientation="Horizontal" HorizontalOptions="CenterAndExpand">

                        <Frame CornerRadius="50"

                               HeightRequest="48"

                               WidthRequest="48"

                               HasShadow="false"

                               BackgroundColor="#d7716c"

                               BorderColor="#a72321"

                               Padding="8"

                               HorizontalOptions="Center"

                               VerticalOptions="Center">

                            <Image Source="{Binding ImageSupp}"

                                    WidthRequest="42"

                                    HeightRequest="42"

                                    HorizontalOptions="CenterAndExpand"

                                    VerticalOptions="CenterAndExpand">

                            </Image>

                        </Frame>

                    </StackLayout>

                    <StackLayout Grid.Row="1" Orientation="Vertical" VerticalOptions="Start" HorizontalOptions="CenterAndExpand">

                        <Label TextColor="Black"

                                               FontSize="13"

                                               FontAttributes="Bold"

                                               Text="{Binding Supporto}"

                                               HorizontalOptions="CenterAndExpand"

                                               VerticalOptions="Start"/>

                        <Label TextColor="Black"

                                               FontSize="12"

                                               Text="{Binding EmailSupp}"

                                               HorizontalOptions="CenterAndExpand"/>

                        <Label TextColor="Black"

                                               FontSize="12"

                                               Text="{Binding TelefonoSupp}"

                                               HorizontalOptions="CenterAndExpand"/>

                    </StackLayout>

                </Grid>

            </Grid>

            <Grid Grid.Row="1" Padding="0,0,0,10">

                <BoxView VerticalOptions="Center"

                           HorizontalOptions="Center"

                           HeightRequest="1"

                           WidthRequest="50"

                           Color="#5b5d68"></BoxView>

            </Grid>

            <Grid Grid.Row="2" Padding="0,0,0,20">

                <Grid>

                    <Grid.RowDefinitions>

                        <RowDefinition Height="Auto"/>

                        <RowDefinition Height="Auto"/>

                    </Grid.RowDefinitions>

                    <StackLayout Grid.Row="0" Orientation="Horizontal" HorizontalOptions="CenterAndExpand">

                        <Frame CornerRadius="50"

                               HeightRequest="48"

                               WidthRequest="48"

                               HasShadow="false"

                               BackgroundColor="#d7716c"

                               BorderColor="#a72321"

                               Padding="8"

                               HorizontalOptions="Center"

                               VerticalOptions="Center">

                            <Image Source="{Binding ImageComm}"

                                    WidthRequest="42"

                                    HeightRequest="42"

                                    HorizontalOptions="CenterAndExpand"

                                    VerticalOptions="CenterAndExpand"></Image>

                        </Frame>

                    </StackLayout>

                    <StackLayout Grid.Row="1" Orientation="Vertical" VerticalOptions="Start" HorizontalOptions="CenterAndExpand">

                        <Label TextColor="Black"

                                               FontSize="13"

                                               FontAttributes="Bold"

                                               Text="{Binding Commerciale}"

                                               HorizontalOptions="CenterAndExpand"

                                               VerticalOptions="Start"/>

                        <Label TextColor="Black"

                                               FontSize="12"

                                               Text="{Binding EmailComm}"

                                               HorizontalOptions="CenterAndExpand"/>

                        <Label TextColor="Black"

                                               FontSize="12"

                                               Text="{Binding TelefonoComm}"

                                               HorizontalOptions="CenterAndExpand"/>

                    </StackLayout>

                </Grid>

            </Grid>

            <Grid Grid.Row="3"

                  HorizontalOptions="CenterAndExpand"

                  VerticalOptions="Start">

                <ScrollView>

                <StackLayout>

                    <Grid>

                        <Grid.RowDefinitions>

                            <RowDefinition Height="Auto"/>

                            <RowDefinition Height="Auto"/>

                            <RowDefinition Height="Auto"/>

                            <RowDefinition Height="Auto"/>

                        </Grid.RowDefinitions>

                        <inputLayout:SfTextInputLayout x:Name="Input1"

                                                       Grid.Row="1"

                                                       Hint="NAME"

                                                       HeightRequest="70"

                                                       ContainerType="Outlined"

                                                       EnableHintAnimation="True"

                                                       AutomationId="textInputLayout"

                                                       FocusedColor="#a72321"

                                                       UnfocusedColor="DarkGray"

                                                       ErrorColor="#a72321">

                                <inputLayout:SfTextInputLayout.Triggers>

                                    <DataTrigger TargetType="inputLayout:SfTextInputLayout"

                                                 Binding="{Binding Source={x:Reference nome},Path=Text.Length}"

                                                 Value="0">

                                        <Setter Property="ErrorText" Value="*Campo richiesto" />

                                        <Setter Property="HasError" Value="True"/>

                                    </DataTrigger>

                                </inputLayout:SfTextInputLayout.Triggers>

                                <Entry x:Name="nome" Placeholder=""/>

                        </inputLayout:SfTextInputLayout>

                            <inputLayout:SfTextInputLayout x:Name="Input2"

                                                           Hint="Denominazione impresa" Grid.Row="2"

                                                           HeightRequest="70"

                                                           ContainerType="Outlined"

                                                           EnableHintAnimation="True"

                                                           AutomationId="textInputLayout"

                                                           FocusedColor="#a72321"

                                                           UnfocusedColor="DarkGray"

                                                           ErrorColor="#a72321">

                                <inputLayout:SfTextInputLayout.Triggers>

                                    <DataTrigger TargetType="inputLayout:SfTextInputLayout"

                                                 Binding="{Binding Source={x:Reference denominazione},Path=Text.Length}"

                                                 Value="0">

                                        <Setter Property="ErrorText" Value="*Campo richiesto" />

                                        <Setter Property="HasError" Value="True"/>

                                    </DataTrigger>

                                </inputLayout:SfTextInputLayout.Triggers>

                            <Entry x:Name="denominazione" Placeholder="" IsPassword="True" />

                        </inputLayout:SfTextInputLayout>

                            <inputLayout:SfTextInputLayout x:Name="Input3"

                                                            Hint="Indirzzo Email" Grid.Row="3"

                                                            HeightRequest="70"

                                                            ContainerType="Outlined"

                                                            EnableHintAnimation="True"

                                                            AutomationId="textInputLayout"

                                                            FocusedColor="#a72321"

                                                            UnfocusedColor="DarkGray"

                                                            ErrorColor="#a72321">

                                <inputLayout:SfTextInputLayout.Triggers>

                                    <DataTrigger TargetType="inputLayout:SfTextInputLayout"

                                                 Binding="{Binding Source={x:Reference email},Path=Text.Length}"

                                                 Value="0">

                                        <Setter Property="ErrorText" Value="*Campo richiesto" />

                                        <Setter Property="HasError" Value="True"/>

                                    </DataTrigger>

                                </inputLayout:SfTextInputLayout.Triggers>

                            <Entry x:Name="email" Placeholder="" IsPassword="True" />

                        </inputLayout:SfTextInputLayout>

                        <inputLayout:SfTextInputLayout Hint="Telefono"

                                                       Grid.Row="4"

                                                       HeightRequest="70"

                                                       ContainerType="Outlined"

                                                       EnableHintAnimation="True"

                                                       AutomationId="textInputLayout"

                                                       FocusedColor="#a72321"

                                                       UnfocusedColor="DarkGray">

                            <Entry x:Name="telefono" Placeholder="" IsPassword="True" />

                        </inputLayout:SfTextInputLayout>

                            <comboBox:SfComboBox x:Name="comboBox"

                                                 HeightRequest="70"

                                                 MultiSelectMode="None"

                                                 DisplayMemberPath = "Tipoligia di richiesta"

                                                 SelectionChanged="ComboBox_SelectionChanged">

                            </comboBox:SfComboBox>

                            <button:SfButton Text="OPEN TICKET" Grid.Row="5"

                                         BackgroundColor="#a72321"

                                         CornerRadius="5"

                                         FontAttributes="Bold"

                                         HeightRequest="40"

                                         WidthRequest="100"

                                         HorizontalOptions="End"

                                         VerticalOptions="StartAndExpand"

                                         Clicked="SfButton_Clicked">

                                <button:SfButton.BackgroundGradient>

                                    <gradient:SfRadialGradientBrush Radius="7.0">

                                        <gradient:SfRadialGradientBrush.GradientStops>

                                            <gradient:SfGradientStop Color="#de3d34" Offset="0"/>

                                            <gradient:SfGradientStop Color="#fdc269" Offset="1"/>

                                        </gradient:SfRadialGradientBrush.GradientStops>

                                    </gradient:SfRadialGradientBrush>

                                </button:SfButton.BackgroundGradient>

                            </button:SfButton>

                    </Grid>

                </StackLayout>

                </ScrollView>

            </Grid>

        </Grid>

        <Button Text="CLOSE"

                   TextColor="White"

                   BackgroundColor="#a72321"

                   Clicked="Button_Clicked"

                   VerticalOptions="EndAndExpand"

                   HorizontalOptions="FillAndExpand">

        </Button>

    </StackLayout>

</ContentPage>


Thank you




1 Reply

SR Shivani Ramakrishnan Syncfusion Team October 17, 2022 09:06 AM UTC

Hi Fabio,

 

Query: How To Bind Multiple ViewModels In A Single Page?

 

We have looked into your query. We can bind multiple viewmodels using the BindingContext of a particular control. Here is the code snippet:

<comboBox:SfComboBox x:Name="comboBox"
                                                 HeightRequest="70"
                                                 MultiSelectMode="None"                                              
                                                 DataSource="{Binding Employees}"                                               
                                                 DisplayMemberPath="Name"
                                                 SelectionChanged="ComboBox_SelectionChanged">                            
                                <comboBox:SfComboBox.BindingContext>                                    
                                    <local:ComboBoxViewModel/>                                    
                                </comboBox:SfComboBox.BindingContext>

                            </comboBox:SfComboBox>

 

                                         ..........................................

                                         ..........................................

                                         ..........................................

 

                  <Button Text="CLOSE"
                   TextColor="White"
                   BackgroundColor="#a72321"
                   Command="{Binding ButtonCommand}"
                   VerticalOptions="EndAndExpand"
                   HorizontalOptions="FillAndExpand">
            <Button.BindingContext>               
                <local:ButtonViewModel/>          
            </Button.BindingContext>

        </Button>

 


We have attached a sample for your reference, which can be downloaded from the attachment. If your requirement is different, please explain to us briefly about your requirement. It will be helpful for providing a solution at the earliest.

 

Please let us know if you need any other details.

 

Regards,
Shivani


Attachment: ComboBoxSample_598ed288.zip

Loader.
Up arrow icon