I'm new to WPF MVVM, and a bit stuck. I need to switch between about 100 different tables on the same view using MVVM with wpf. I have Treeview with the list of table names and on item selection the correct DataGrid has to be displayed beside the Treeview. I created Model and ViewModel classes for each table. However, how do I select the right Viewmodel to bind depend on the selection.
1
votes
It would help if we know what you code looks like. You could use the same ViewModel for one TreeView entry and one DataGrid e.g.
– Mighty Badaboom
Hello Mighty, All I'm currently have my model and viewmodel classes with INotifyPropertyChanged. I'm trying to implement what Peter suggested, but still not much success.
– Vadim
1 Answers
0
votes
If I understand your problem right - then you have a design problem.
First get the SelectedItem
of your TreeView
To use the SelectedItem
-Binding
on a TreeView see this. But you could do also the bad way in the code behind.
Second bind your SelectedItem
So what you want to do is:
bind the SelectedItem
on something like a ContentControl
or ContentPresenter
. Or do it the bad way in the code behind.
For example like this:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TreeView ItemsSource="{Binding MyItemSource}">
<!-- Get the selected item here (watch how to in the linked answer) -->
</TreeView>
<ContentPresenter Grid.Column="1"
Content="{Binding Path=SelectedItem}"
>
<ContentPresenter.ContentTemplate>
<DataTemplate>
<DataGrid>
<!-- Your DatGrids or what ever -->
</DataGrid>
</DataTemplate>
</ContentPresenter.ContentTemplate>
</ContentPresenter>
</Grid>
Third (optional) If you have different DataGrids
You could also use a DataTemplateSelector to change your Views depending on your SelectedItem too. You would use it on the ContentPresenter
in this example.