question

rameshraja-6484 avatar image
0 Votes"
rameshraja-6484 asked CobyGifford-5195 commented

How to assosiate two ViewModels with Single View in WPF, C#

Hi All,

I am new to MVVM , I have one basic doubt ,

How can I use two View Models in a Single View .

If any sample sudo code would be appreciated .

Regards
Rams

windows-wpf
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

DaisyTian-1203 avatar image
0 Votes"
DaisyTian-1203 answered rameshraja-6484 commented

Create two new UserControls named View1 and View2 as below:
Code for View1.xaml

 <Grid>
         <DataGrid AutoGenerateColumns="False" DataContext="{Binding Model1s}" ItemsSource="{Binding }"  >
             <DataGrid.Columns>
                 <DataGridTextColumn Header="ID" Binding="{Binding ID}" />
                 <DataGridTextColumn Header="Name" Binding="{Binding Name}" />
             </DataGrid.Columns>
         </DataGrid>
     </Grid>

Code for View2.xaml

   <Grid>
         <DataGrid DataContext="{Binding Model2s}" AutoGenerateColumns="False" ItemsSource="{Binding }">
             <DataGrid.Columns>
                 <DataGridTextColumn Header="Name" Binding="{Binding Name}" />
                 <DataGridTextColumn Header="Sex" Binding="{Binding Sex}" />
             </DataGrid.Columns>
         </DataGrid>
     </Grid>

Code for MainWindow.xaml

  <Window.Resources>
         <DataTemplate DataType="{x:Type local:ViewModel1}">
             <local:View1/>
         </DataTemplate>
         <DataTemplate DataType="{x:Type local:ViewModel2}">
             <local:View2/>
         </DataTemplate>
     </Window.Resources>
    
     <Window.DataContext>
         <local:MainWindowViewModel />
     </Window.DataContext>
     <StackPanel>
         <ContentControl Name="Con1" Content="{Binding CurrentView1}" />
         <ContentControl Name="Con2" Content="{Binding CurrentView2}" />
     </StackPanel>

Code for MainWindowViewModel.cs

 public class MainWindowViewModel
     {
         private object _currentView1;
         private object _currentView2;
         private object _view1;
         private object _view2;
         public MainWindowViewModel()
         {
             _view1 = new View1();
             _view2 = new View2();
             Model1s = new ViewModel1().Model1s;
             Model2s = new ViewModel2().Model2s;
             CurrentView1 = _view1;
             CurrentView2 = _view2;
         }
    
         public object CurrentView1
         {
             get { return _currentView1; }
             set
             {
                 _currentView1 = value;
             }
         }
    
         public object CurrentView2
         {
             get { return _currentView2; }
             set
             {
                 _currentView2 = value;
             }
         }
    
         public ObservableCollection<Model1> Model1s { get; set; } = new ObservableCollection<Model1>();
            
         public ObservableCollection<Model2> Model2s { get; set; } = new ObservableCollection<Model2>();
    
     }

Is it what you want? If it is not, please ponit out and give me more details to analyze.


If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

· 3
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

HI DiasyTian ,

Thank you so much for wondurfull example.

this is what iam looking .

can you please answer my first two question in previous thread .

1) May I know is it correct having two DataContext in single View ?
2) Is not breaking any MVVM fundamental like One -View to One View Model ? if this question is wrong pls correct me.

0 Votes 0 ·

@rameshraja-6484
Answer 1: Each view has one DataContext, and it can contain many container controls which has own DataContext.

Answer 2: I think if you are strict about your following of the pattern then each view has just one ViewModel. In In practical application, if the requirements change in the middle of the process, the easiest way is to have the view reference two different viewmodels.

0 Votes 0 ·

most welcome answer .
#2 Answer , so can I consider one View to One ViewModel is not mandatory in MVVM ?

0 Votes 0 ·
DuaneArnold-0443 avatar image
0 Votes"
DuaneArnold-0443 answered

A viewmodel is a class/object. A viewmodel can contain an instance of class/object within it.

public class TestVM1
{

  public string FirstName {get; set;}

  public TestVM2 Testvm2 {get; set;) = new TestVM2();

}

public class TestVM2
{

 public string Address {get; set:}

}

==============

some code somewhere in the project.

TestVM1 testvm1 = new TestVM1();

testvm1.FirstName = 'Larry";

testvm1.Testvm2.Address = "77 Hollywood Blvd";

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

DaisyTian-1203 avatar image
1 Vote"
DaisyTian-1203 answered CobyGifford-5195 commented

I will show you a demo of binding two viewmodels in one view.

Code for Model1:

 public class Model1
     {
         public string Name { get; set; }
         public int ID { get; set; }
     }
    
    
     public class Model2
     {
         public string Name { get; set; }
         public string Sex { get; set; }
     }

Code for ViewModels:

  public class ViewModel1
     {
         public ViewModel1()
         {
             Model1s = new ObservableCollection<Model1>()
             {
             new Model1() { Name = "Jim", ID = 1 },
             new Model1() { Name = "Red", ID = 2 },
             new Model1() { Name = "Green", ID = 3 } ,
             new Model1() { Name = "Black", ID = 4 }
             };
    
               
         }
         public ObservableCollection<Model1> Model1s { get; set; }
     }
    
    
     public class ViewModel2
     {
         public ViewModel2()
         {
             Model2s = new ObservableCollection<Model2>()
             {
             new Model2() { Name = "Jack", Sex = "Boy" },
             new Model2() { Name = "Dais", Sex = "Girl" },
             new Model2() { Name = "Peter", Sex = "girl" } ,
             new Model2() { Name = "Black", Sex = "Boy" }
             };
    
    
         }
         public ObservableCollection<Model2> Model2s { get; set; }
     }

Code for View:

  <Window.Resources>
         <local:ViewModel1 x:Key="MyViewModel1"></local:ViewModel1>
         <local:ViewModel2 x:Key="MyViewModel2"></local:ViewModel2>
     </Window.Resources>
     <StackPanel>
         <Grid>
             <DataGrid DataContext="{StaticResource MyViewModel1}" AutoGenerateColumns="False" ItemsSource="{Binding Model1s}" >
                 <DataGrid.Columns>
                     <DataGridTextColumn Header="ID" Binding="{Binding ID}" />
                     <DataGridTextColumn Header="Name" Binding="{Binding Name}" />
                 </DataGrid.Columns>
             </DataGrid>
         </Grid>
    
         <Grid>
             <DataGrid DataContext="{StaticResource MyViewModel2}" AutoGenerateColumns="False" ItemsSource="{Binding Model2s}" >
                 <DataGrid.Columns>
                     <DataGridTextColumn Header="Name" Binding="{Binding Name}" />
                     <DataGridTextColumn Header="Sex" Binding="{Binding Sex}" />
                 </DataGrid.Columns>
             </DataGrid>
         </Grid>
     </StackPanel>

The result picture is:
68388-capture.png


If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


capture.png (6.3 KiB)
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thank you very muchh for extend support. very simple and clear example is this.

May I know is it correct having two DataContext in single View ?
2) Is not breaking any MVVM fundamental like One -View to One View Model ?

3) can you show above sample by using datattemplate like below

  <DataTemplate DataType="{x:Type vmodels:MyViewModel1}">

<views:MyView DataContext="{Binding}" />
</DataTemplate>

Please correct me if my query wrong .

Regards
Rams

0 Votes 0 ·

Thanks @DaisyTian-1203...this saved me after much time trying. Works perfectly.

0 Votes 0 ·