Adding/removing elements to a panel dynamically
Panels contain elements that are typically added in XAML as a base for the user interface. Sometimes, however, we need to add or remove elements dynamically at run time based on user actions or other criteria. Let's see how this can be done.
Getting ready
Make sure Visual Studio is up and running.
How to do it...
We'll create a simple circle drawing program. Every click adds a circle to a Canvas
.
- Create a new WPF application named
CH03.PaintingCircles
. - Open
MainWindow.xaml
. Replace the defaultGrid
with aCanvas
, name it_canvas
, and set itsBackground
toWhite
. - Add an event handler for the
MouseUp
event to theCanvas
:<Canvas x:Name="_canvas" Background="White" MouseUp="OnClickCanvas"> </Canvas>
- Navigate ...
Get Windows Presentation Foundation 4.5 Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.