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.
Asked
Active
Viewed 733 times
1
-
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 Mar 08 '17 at 10:21
-
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 Mar 08 '17 at 18:33
1 Answers
0
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.
-
would it make sense to combine several viewmodels into the one that is working with the view directly binding the selected model?
ObservableCollection
– Vadim Mar 09 '17 at 15:17 -
You have the right idea, but bad execution. Build your stuff with a hierarchie. So the `SelectedModel ` is a ViewModel and not a collection mate!!! Obviously the `SelectedModel` has a Field of Type ObservableCollection
. – Peter Mar 10 '17 at 09:22