Rectangle In WPF

The Rectangle object represents a rectangle shape and draws a rectangle with the given height and width. The Width and Height properties of the Rectangle class represent the width and height of a rectangle. The Fill property fills the interior of a rectangle. The Stroke property sets the color and StrokeThickness represents the width of the outer line of a rectangle.

Creating a Rectangle

The Rectangle element in XAML creates a rectangle shape. The following code snippet creates a rectangle by setting its width and height properties to 200 and 100 respectively. The code also sets the black stroke of width 4.

  1. <Rectangle Width="200" Height="100" Fill="Blue" Stroke="Black" StrokeThickness="4" />

The output looks like Figure 5.

Rectangle In WPF
Figure 5. A rectangle

The CreateARectangle method listed in Listing 8 draws same rectangle in Figure 5 dynamically.

  1. ///<summary>
  2. /// Creates a blue rectangle with black border
  3. ///</summary>
  4. publicvoid CreateARectangle()
  5. {
  6. // Create a Rectangle
  7. Rectangle blueRectangle = newRectangle();
  8. blueRectangle.Height = 100;
  9. blueRectangle.Width = 200;
  10. // Create a blue and a black Brush
  11. SolidColorBrush blueBrush = newSolidColorBrush();
  12. blueBrush.Color = Colors.Blue;
  13. SolidColorBrush blackBrush = newSolidColorBrush();
  14. blackBrush.Color = Colors.Black;
  15. // Set Rectangle's width and color
  16. blueRectangle.StrokeThickness = 4;
  17. blueRectangle.Stroke = blackBrush;
  18. // Fill rectangle with blue color
  19. blueRectangle.Fill = blueBrush;
  20. // Add Rectangle to the Grid.
  21. LayoutRoot.Children.Add(blueRectangle);
  22. }

Listing 7

The RadiusX and RadiusY properties set the x-axis and y-axis radii of the ellipse that is used to round the corner of a rectangle. By adding the following lines of code to Listing 7 creates a rounded rectangle, which looks like Figure 6.

  1. // Set roundness
  2. blueRectangle.RadiusX = 20;
  3. blueRectangle.RadiusY = 20;
Rectangle In WPF
Figure 6. A rounded rectangle

    Up Next
      Ebook Download
      View all
      Learn
      View all
      sourabhsomani.com