WPF C# Tutorial – running a for each loop for controls in Visual Studio
- Subject: WPF C# Tutorials
- Learning Time: 1 Hour
In this tutorial we will show you how to run a for each loop in WPF using C#. For each loop is very useful when it comes to identifying children object from a WPF form. This way we can identify rectangles, buttons, labels, textboxes and images inside the app and give them instructions on what we want to do. In games development for each is very useful because it allows us to search for items dynamically without having to identify them using their names. This will be another quick tutorial just to show this method and we will build on it as we progress more in to WPF programming.
Lesson Objective –
- Create a WPF form application in Visual studio
- Use Rectangles and apply various fill/colours to them
- Use for each loop in C# and identify these controls inside the app
- Apply tags to each rectangle in the app and customise them differently from the same for each loop
Start a new project in visual studio, call this project For each loop and click OK.
Make sure you save this project in a location where you can find them later on.
This is the default view of our app, we can start adding our items to this form.
Before the TITLE tag add Background = “Black” and you see the main window background colour changes to black. WPF allows us to customise the app any way we want so you can try out some other colours if you prefer.
Add the following line in the Title Tag, This line will make sure that the CANVAS which we will add next will be focused on when the app is loaded.
Delete the GRID Tag from the code and add CANVAS to it, this canvas will have a name called MyCanvas and also set focusable to true.
All the elements for this app will be added inside the CANVAS tags
Here are all of the rectangles we need for this app, if you see the code they all have very similar properties so lets break down one of the lines which will help you understand all of.
We start with the rectangle keyboard <Rectangle it has a width of 50 pixels and height of 50 pixels, margin is set to 0 pixels. The location of the first rectangle is 10 pixels from the left of the main canvas and 10 pixels from the top of the main canvas. It has a light clue fill colour and has a tag attached called coin /> the last two symbols represent end of the rectangle tag. When the program loads it will take all of these code from the beginning of the to the end and it will render on the screen. If you have done it correctly then you should see this on your screen.
Nice, looking good already.
XAML code for this app –
<Window x:Class="For_Each_Loop.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:For_Each_Loop" mc:Ignorable="d" Background="Black" Title="MainWindow" Height="350" Width="525" FocusManager.FocusedElement="{Binding ElementName=MyCanvas}"> <Canvas Name="MyCanvas" Focusable="True"> <Rectangle Width="50" Height="50" Margin="0" Canvas.Left="10" Canvas.Top="10" Fill="LightBlue" Tag="coin" /> <Rectangle Width="50" Height="50" Margin="0" Canvas.Left="10" Canvas.Top="141" Fill="LightBlue" Tag="coin" /> <Rectangle Width="50" Height="50" Margin="0" Canvas.Left="10" Canvas.Top="261" Fill="LightBlue" Tag="coin" /> <Rectangle Width="50" Height="50" Margin="0" Canvas.Left="235" Canvas.Top="261" Fill="Coral" Tag="platform"/> <Rectangle Width="50" Height="50" Margin="0" Canvas.Left="235" Canvas.Top="10" Fill="Coral" Tag="platform"/> <Rectangle Width="50" Height="50" Margin="0" Canvas.Left="235" Canvas.Top="141" Fill="Coral" Tag="platform"/> <Rectangle Width="50" Height="50" Margin="0" Canvas.Left="458" Canvas.Top="261" Fill="Plum" Tag="thing"/> <Rectangle Width="50" Height="50" Margin="0" Canvas.Left="458" Canvas.Top="10" Fill="Plum" Tag="thing"/> <Rectangle Width="50" Height="50" Margin="0" Canvas.Left="458" Canvas.Top="141" Fill="Plum" Tag="thing"/> </Canvas> </Window>
Double check this code with the ones you have see if all of it is as above.
C# Programming –
XAML works together with C#, we can design the program in using these syntax’s but we need add our functionalities in C#.
Go to the solutions explorer
Click on the little arrow in front of the main window XAML file and it will show a main window XAML CS file under it, double click on it and it will open in Visual Studio.
This is the default code view for this app, we will add our own codes into this and make it interact with the rectangles created earlier.
Create a new function called run Loop, this is a public function and since its not returning any data back to the app we can leave it as void.
Add the following code inside this function.
public void runLoop() { // below is the for each loop, we will check each of children items in the canvas // if they match our query then we can foreach (var x in MyCanvas.Children.OfType<Rectangle>()) { // we are strinctly search for rectangles in this loops if ((string)x.Tag == "coin") { // in this if statement we check if this rectangle has a coin tag // then we can do the following x.Stroke = Brushes.Yellow; // add a yellow border to it x.StrokeThickness = 4; // set border thickness to 4 } if ((string)x.Tag == "platform") { // in this if statement we check if this rectangle has a platform tag // then we can do the following x.Stroke = Brushes.LightGreen; // add light green border to it x.StrokeThickness = 4; // set border thinkness to 4 } if ((string)x.Tag == "thing") { // in this if statemtn we check if this rectangle has a thing tag // then we can do the following x.Stroke = Brushes.LightSkyBlue; // add a light sky blue border to it x.StrokeThickness = 4; // set border thickness to 4 } } }
This is run loop function codes; inside this function we have one main loop running and inside that loop we have given it instruction on what to do when it finds the items we are looking for. Let’s break it down and see what it does.
This is the loop structure –
foreach (var x in MyCanvas.Children.OfType<Rectangle>()) { }
First, we start with foreach keyword and then inside the brackets we can tell the loop what are we looking for. We want to find all the rectangles in this app so we create VARIABLE called x. This variable will be useful to identify the rectangles we need to make this app work. Then we are checking all of the children items inside the MyCanvas and we specifically want to look for Rectangle type objects in this case. After that we close the bracket and start and close the curly brackets for the loop. All of the further instructions will be inside the curly brackets
if ((string)x.Tag == "coin") { // in this if statement we check if this rectangle has a coin tag // then we can do the following x.Stroke = Brushes.Yellow; // add a yellow border to it x.StrokeThickness = 4; // set border thickness to 4 }
Above is the if statement we need in order to differentiate the queries for this app, if we just ran and the loop then we will find all of the rectangles that’s present in the canvas, but we did include a tag for each of the rectangles so we can do different things with them when we find it in the loop. In this case we just want to find the STRING for the specific items in the loop, so we can say that look for the TAG inside of X (which was the variable declared for this loop) and IF this X has a TAG that’s equals to COIN then we can add a border colour YELLOW to this rectangle and set the border thickness to 4 pixels.
Rest the IF statements follow the same principle. If you ran this app now, it wont do any of this because we haven’t called this function yet. This function is correct but it needs to be called in order for these instructions to be carried out.
Add the following line in the main window function just under the initialize component line.
Click on the start button from the tool box and then you can see what the program now does.
As you can see in the picture above, each of the columns have different borders on them when the program runs. This app is looking for the tags on each of the rectangles and will apply the styles we instructed in the code. If we had to do this manually we would have coded it in the XAML file and that would have been a long process. Using foreach loop is saving us time and also makes the app more memory efficient.
As you can see now we have nice thick borders around the rectangles. Well done.
Full C# Code –
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace For_Each_Loop { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); runLoop(); // call the run loop function } public void runLoop() { // below is the for each loop, we will check each of children items in the canvas // if they match our query then we can foreach (var x in MyCanvas.Children.OfType<Rectangle>()) { // we are strinctly search for rectangles in this loops if ((string)x.Tag == "coin") { // in this if statement we check if this rectangle has a coin tag // then we can do the following x.Stroke = Brushes.Yellow; // add a yellow border to it x.StrokeThickness = 4; // set border thickness to 4 } if ((string)x.Tag == "platform") { // in this if statement we check if this rectangle has a platform tag // then we can do the following x.Stroke = Brushes.LightGreen; // add light green border to it x.StrokeThickness = 4; // set border thinkness to 4 } if ((string)x.Tag == "thing") { // in this if statemtn we check if this rectangle has a thing tag // then we can do the following x.Stroke = Brushes.LightSkyBlue; // add a light sky blue border to it x.StrokeThickness = 4; // set border thickness to 4 } } } } }