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.