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

ramesh raja 21 Reputation points
2021-02-15T16:11:17.127+00:00

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 Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,774 questions
0 comments No comments
{count} votes

Accepted answer
  1. DaisyTian-1203 11,621 Reputation points
    2021-02-17T04:36:38.67+00:00

    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.


2 additional answers

Sort by: Most helpful
  1. DaisyTian-1203 11,621 Reputation points
    2021-02-16T02:03:12.397+00:00

    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.

    1 person found this answer helpful.

  2. Duane Arnold 3,221 Reputation points
    2021-02-15T23:38:42.247+00:00

    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";

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.