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 to the event handler you just created. We want a left-click to add an ellipse where the mouse pointer is and a right-click to make an
Ellipse
under the cursor disappear.Add the following code to the event handler in case...