I came across a situation where I have to display different user control depends on the selection of item in tree control. While doing internet searching I found this article WPF application with dynamic user controls as page. This application loads different user control based on the button click. My application is based on the same idea, but I used tree control rather than button.
I created a simple data structure to store the department name and subjects to display in tree control and three user controls (one for each department). In my user control I didn’t do anything but just display a text message in the text block to show which user control is loaded right now.
The whole idea is picked from the above mention article to create a dictionary of string as a key and instance of user control as a value. Then inside the InitializeComponent method create all the user control object and place it in dictionary. I selected the department name as a key. Here is a code of it.
We created one group box as a container to load the user control at run time. Because we have define the course id for each course and it varies from department to department, therefore we can display the appropriate user control after looking at the id of the selected course. Here is a code to load the appropriate and set it as a content of the group box. Here is a code of SelectedItemChanged event of tree view.
Rest of the application is very straight forward. Here is a complete XAML code of the main window of the application.
Here is complete C# code of the program.
Here is a XAML for one user control. All of the user controls are very similar.
And here is C# code of the same user control.
This is the output of the program if we select some math subject.
And here is the output if we select any subject from Computer Science.