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.

  1. Create a new WPF application named CH03.PaintingCircles.
  2. Open MainWindow.xaml. Replace the default Grid with a Canvas, name it _canvas, and set its Background to White.
  3. Add an event handler for the MouseUp event to the Canvas:
    <Canvas x:Name="_canvas" Background="White" 
  4. Navigate ...

Get Windows Presentation Foundation 4.5 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.