Pixentia Insights

Dynamic Windows Creation using WPF

Written by Pixentia | Jul 9, 2015 12:49:00 PM

Overview : Basically for a WPF application, it will have only one Main Window. In that we can add many of the user controls depending on the requirement. In some scenarios, we may need to display other windows from our current application. This blog will help you to show how to create windows dynamically from a WPF application, in such cases.


Application Use case : Our application contains two UserControls, which will instantiate the Window that dynamically loads and prompts the user to enter some text. Upon entering text, the response will be send back to their respective Views.

Software & Technologies Used:

  • Microsoft Visual Studio 2013(.Net Framework 4.5).
  • FirstFloor.ModernUI.dll
  • WPF Technology with MVVM Framework

Implementation:

Create a WPF application as below which will be the view project.

Add other two class libraries, one is for Models and the other is for ViewModels.

Add a reference of Modern UI dll into View and ViewModel’s project, which can be installed via Nuget Packages. Using this dll, we can create Modern UI controls for better look and feel than normal WPF controls.

Create a Main Window using Modern UI and place a UserControl (PWPMain.xaml) in between the links tags which will act as a container for other Controls.

In PWPMainViewModel, add the below logic in the View loading event.

Above code adds two user controls dynamically of type PromptOriginViewModel in a single row within grid control and that grid control will be in the PWPMain. After generating the views, call the ShowPrompt method to generate the dynamic windows.

ShowPrompt () method contains the following code:

Used TPL (Task Parallel Library) to generate number of dynamic windows parallelly depending on the requirement. In our scenario we are creating two, one from each user control.

  • For that Dynamic window, we are providing the tag and title with unique values in order to differentiate from which user control it was creating.
  • Assign our current Application Window as owner to the dynamic window so that it appears above it.
  • Finally, show the dynamic window using window.show () method.

XAML for dynamic window is as follows:

Above XAML contains a label, text box and a button. On loading the application, both user controls prompts a window of above view type to the user for his response text. After entering the data into the text box, user clicks ok button to send the response back to that particular UserControl which generated the dynamic prompt window.

 

Pixentia is an enthusiastic family of individuals, fervent to make lives simpler through effective use of technology. Our mission is to implement solutions that drives business results. Know more insights from our thoughts and experience.

Contact us today or call 1-855-978-6816 to talk with us about your business needs.