04Nov
How to implement WPF Canvas? Explain with an example
How to implement WPF Canvas? Explain with an example

What is canvas?

WPF has many layouts, among which the canvas is a popular one. Let us learn something about the canvas. It has some properties and methods. You can make an icon by using Canvas.Right, Canvas.Left, Canvas.Bottom and Canvas.Top coordinators and can make undefined controls.

Canvas is a lightweight layout of WPF. Canvas is used for 2D graphic design elements but not for UI. You cannot use it for making text-box, checkbox, or drop-down because it will create difficulty in screen resolution. Canvas has its height & width, so it cannot be re-sized automatically.

It allows you to put canvas into the canvas. That’s why it can only be used for making drawings. This was the main reason and that’s why developers are not using canvas for creating any controls like text-box, check-box, and Drop-Down. Despite having the support of these things in Canvas, the developer does not use it because of the screen resolution issue with canvas. Hence it is not considered as a UI element.

It has so many properties but the main properties are height and width, you have to set the height & width for the canvas but if you do not set these properties, then your canvas control view will not get created. Because it’s by default the height & width is zero (0). So if you do not set this, it will consider as zero and you cannot see the canvas control view. Thus, it is necessary to set the height and width of canvas control. Canvas has its properties which you can change dynamically as well.

You have to set the values for each property. That’s why, it is known as the simplest layout compare to other layouts like Grid, Stack panel and dock panel, etc.

You can set the canvas in both ways statically and dynamically. If you want to set the canvas statically, then you can do it with.XAML file and if you want to set dynamically, then you can do it with .CS file. We will see the example next.

Now let’s see the common and more used properties of the canvas. By using the canvas properties, you can make a square, triangle, and rectangle. You can make many things by setting the coordinators with some properties.

Properties of the canvas are as follows.

  1. Height & width
  2. Margin
  3. Background
  4. Name
  5. Zindex

1.   Height & width

This is one of the main properties of the canvas.

You can set the value whatever you want to design time. You can also change the value through .cs file you can set other properties like min-height, max-height, min-width and max-width.

If you want to check the canvas for the run-time, then you can check it by setting the actual height & actual width

example

<canvas height=”20” width=”30”>

..

</canvas>

2.   Margin

Thus, the property of canvas is used for how much space you want to keep from the left or right. It is used for design purpose. You have to set numeric values for this property which you can set in 3 different ways

1. <canvas margin=”10”>

2. <canvas margin=”10 20”>

3. <canvas margin=”10 5 10 5”>

3.1  <canvas margin=”10”>

It will leave equal space from left, right, top, and bottom.

3.2 <canvas margin=”10 20”>

In this, there are two parameters the first parameter is for left & right and the second parameter is for top and bottom. So the first parameter is 10 which             will leave space from left & right, and the second parameter 20 which will leave space from the top & bottom

<canvas margin=”10 20”>

3.3  <canvas margin=”10 20 15 25”>

10 which will set margin for left
20 which will set margin for the top
15 which will set margin for right
25 which will set margin for bottom

3. Background

This Property is used to fill the color of the canvas.

<canvas Background =” Blue”>

4. Name

It is not a very important property in case if you want to do canvas design from a statically XAML file. But, if you want to change the value dynamically, then for the reference you have to use name property.

You can use the event handler as a name property. For every canvas control, there is an identifier.

<canvas name = ”OurCanvas”>

5. Zindex

The zindex property of canvas is used for indexing the canvas. By giving index, you can easily find which control is behind or which control is overlaying and giving the full view just through sorting index property.

The control which has less index value stays behind and the control which has more zindex value stays in front and overlaps that control.

Indexing is done in ascending order so that the control having more index numbers would be shown.

Now let’s see the example of making a statistical and dynamic canvas.

1. Statistical canvas (.XAML file)

<Canvas Background="Brown">
 	<Rectangle Canvas.Left="10" Canvas.Top="10" Height="50" Width="200" Fill="Orange" />
 	<Rectangle Canvas.Left="10" Canvas.Top="60" Height="50" Width="200" Fill="white"https://soshace.com/>
 	<Rectangle Canvas.Left="10" Canvas.Top="110" Height="50" Width="200" Fill="Green" />
</Canvas>

Output

Statistical canvas Output
Statistical canvas Output

2.   Dynamic canvas(.cs File)

When the page loads canvas will create

public Window()
        {
            InitializeComponent();
            Canvas canvasPanel = new Canvas();   
            canvasPanel.Background = new SolidColorBrush(Colors.RosyBrown);

            //Create orange Rectangle
            Rectangle orangeRectangle = new Rectangle();//obj
            //Properties sets
            orangeRectangle.Width = 150;
            orangeRectangle.Height = 150;
            orangeRectangle.Stroke = new SolidColorBrush(Colors.Black);
            orangeRectangle.Fill = new SolidColorBrush(Colors.Orange);
            Canvas.SetLeft(orangeRectangle, 30);
            Canvas.SetTop(orangeRectangle, 30);
            canvasPanel.Children.Add(orangeRectangle); //Add it

   			//Create pink Rectangle
            Rectangle pinkRectangle = new Rectangle();
            pinkRectangle.Width = 150;
            pinkRectangle.Height = 150;
            pinkRectangle.Stroke = new SolidColorBrush(Colors.Black);
            pinkRectangle.Fill = new SolidColorBrush(Colors.HotPink);   
            Canvas.SetLeft(pinkRectangle, 70);
            Canvas.SetTop(orangeRectangle, 70);
            canvasPanel.Children.Add(pinkRectangle);

  			// Set content of the Window
            RootWindows.Content = canvasPanel;
        }

Output

Dynamic canvas(.cs File) Output-1
Dynamic canvas(.cs File) Output-1

We have seen two different examples of canvas creation but in different ways.

Example:

There is a small example given below to create a canvas. Dynamically adding & removing items from the canvas.

The program is simple when an empty area clicked then it will create a new canvas and again clicked on any canvas control, then it will be removed. All these functionalities would be done by using add or remove.

.XAML File

<Canvas Name="myCanvas" Background="LightPink" MouseLeftButtonDown="RemoveItem">
</Canvas>

.CS File

//create global varible for random color
Brush customcolor;
Random r = new Random();

//MouseEvent for canvas create and remove
privatevoid RemoveItem(object sender, MouseButtonEventArgs e)
{
	if (e.OriginalSource is Rectangle)
	{
		Rectangle activeRectangle = (Rectangle)e.OriginalSource;
        	myCanvas.Children.Remove(activeRectangle); //remove canvas
	}
	else
	{	
		// random color
        	customcolor = new SolidColorBrush(Color.FromRgb((byte)r.Next(1, 255),(byte)r.Next(1, 255), (byte)r.Next(1, 255)));
		//canvas create
        	Rectangle newRectangle = new Rectangle
		{
				//properties set
                	Width = 50,
                	Height = 50,
                	Fill = customcolor,
                	StrokeThickness = 3,
                	Stroke = Brushes.Black
        	};
		//position of mouse click area
        	Canvas.SetLeft(newRectangle, Mouse.GetPosition(myCanvas).X);
        	Canvas.SetTop(newRectangle, Mouse.GetPosition(myCanvas).Y);
		//canvas add
        	myCanvas.Children.Add(newRectangle);
     	}
}

Output

Dynamic canvas(.cs File) Output-2
Dynamic canvas(.cs File) Output-2

Conclusion

In this article, we have learned in detail about how Canvas can be implemented in different ways and understood the importance of different properties of Canvas. The lightweight nature of Canvas attracts the users to utilize it for purposes like 2D design creation, etc.

Author Bio:

Vinod Satapara – Technical Director, iFour Technolab Pvt Ltd

Technocrat and entrepreneur with years of experience building large-scale enterprise web, cloud, and mobile applications using the latest technologies like ASP.NET, CORE, .NET MVC, Angular, and Blockchain. Keen interest in addressing business problems using the latest technologies and have been associated with ASP.NET software development companies.

Leave a Reply