Dynamically adding/removing elements in a panel
So far, we have seen how to add static elements/contents in a Panel
control. But it's not always useful, mainly when you are retrieving data from the backend and populating in the UI or dynamically based on the user interaction.
This recipe will discuss this topic. As all the panels perform similarly to add/remove elements, with a slight difference on the positioning, we will be demonstrating it with a simple Canvas
.
Getting ready
To begin with the coding, let's create a WPF application project first. Open Visual Studio and create a new project named CH03.DynamicPanelDemo
.
How to do it...
Let's add a Canvas
panel inside the window, and dynamically add squares at the current cursor position when the user clicks the Canvas
panel. Perform the following steps:
- Open the
MainWindow.xaml
page and replace the defaultGrid
panel with aCanvas
. - Give it a name. In our example, let's give the name as
canvasPanel
. - Set a background to the canvas panel and register...