In this article I will demonstrate how can you write the code to add the dynamic control on the view via the button click event in WPF with MVVM pattern using prism library.
If you are new in MVVM pattern using Prism Library then you can follow my very first article to start the MVVM and add the dlls into the project from the following:
Now I will show you a demo to add the dynamic control on the view via the click event of a button from the view in view model.
Note:- In this article I am using Visual Studio 2013 and ‘Prism.Unity’ via nugget Packages.
Step 1: Create a project named ‘PrismMVVMTestProject’ of WPF application.
Step 2: It’s a better approach to create the 3 different folders in the project for Model, View and View model respectively.
Step 3: Create pages in all folders,
i. Create a View Named ‘TestView.xaml’ in the Views folder.
ii. Create a Model Named ‘TestModel.cs’ in the Models folder.
iii. Create a ViewModel named ‘TestViewModel.cs’ in the ViewModels folder.
Step 4: Add the namespace named ‘Prism.MVVM’ in the TestModel page to inherit the class named ‘Bindable Base’ and ‘System.Windows.Controls’ for ‘StackPanel’. Create a property named Message where ‘ref‘ parameter allows you to update its value,
Step 5:
a. Add the below namespaces on the TestViewModel page,
b. Create a property of TestModel class object where ‘ref‘ parameter allows you to update its value.
c. Get the stackpanel from the TestView.cs and set it to the model property.
d. Attach a command to the method which will act like event where will add the dynamic label control to the stack panel.
e. Create a dynamic label control and add it to the model property of stackpanel which will reflect on the view.
Step 6:
Step 7: Add ‘PrismMVVMTestProject.ViewModels’ namespace and bind Data Context of TestView Page to the ViewModel named ‘TestViewModel’ constructor with a stack panel as a parameter.
Step 8: Change the ‘StartupUri’ from default page ‘MainWindow’ to ‘TestView’ page,
Run the page and see the output:
After clicking on the ‘Add Label’ button, it will add a dynamic label into the stackpanel
Read more articles on WPF:
View All