Friday, February 11, 2011

Silverlight 3 – Dynamically Add & Remove Objects in C# Code

I recently spent a few minutes trying to figure out how to create rectangles and ellipsis in Silverlight code – I was sure I had it all hooked up and coded properly, but I missed one little thing (isn’t that the way it always goes).

Here is what the canvas looks like in Blend:

Create the dynamic controls:
The following C# code does the heavy lifting to dynamically create an ‘offensive player’ (which is really an ellipse) and associated event handlers and is called by the ‘O’ button click event handler.

public void CreateOffensivePlayer()
// Create an Ellipse
     Ellipse player = new Ellipse();
     player.Height = 25;
     player.Width = 25;

// Create the brushes
     SolidColorBrush blueBrush = new SolidColorBrush();
     blueBrush.Color = Colors.Blue;
     SolidColorBrush blackBrush = new SolidColorBrush();
     blackBrush.Color = Colors.Black;

// Set the width, color and fill
     player.StrokeThickness = 1;
     player.Stroke = blackBrush;
     player.Fill = blueBrush;

// Add to the Canvas
     player.SetValue(Canvas.LeftProperty, _mouseXpos – player.Width / 2);
     player.SetValue(Canvas.TopProperty, _mouseYpos – player.Height / 2);

// Set the tag to identify the player
     string elementName = “offensiveplayer” + (++_offensivePlayerCount).ToString();
     player.Tag = elementName;
     player.Name = elementName;

// Dynamically add the event handlers
     player.MouseEnter += new MouseEventHandler(oPlayer_MouseEnter);
     player.MouseLeave += new MouseEventHandler(player_MouseLeave);

// Add the player to the canvas
Remove the dynamic controls:
The following event handler removes the shapes that were dynamically created on the canvas. It assumes the existance of LayoutRoot and a global _shapeCount integer.

private void btnClearShapes_Click(object sender, System.Windows.RoutedEventArgs e)
    // Make a copy of uielements in order to remove the desired shapes
    UIElement[] tmp = new UIElement[LayoutRoot.Children.Count];
    LayoutRoot.Children.CopyTo(tmp, 0);

    // Iterate the uielements
    foreach (UIElement uielement in tmp)
        Shape myShape = uielement as Shape;

        // Make sure we have a shape and the shape has a tag
        if (myShape != null && myShape.Tag != null)
            // We only want to remove our dynamically created shapes
            if (myShape.Tag.ToString().Contains(“mycustomshape”))

    _shapeCount = 0;

No comments:

Post a Comment