Android Addicted Apps Creator

September 18, 2009

How to make a business rule in BLL and use it wisely

Filed under: WPF — alinberce @ 21:08
Tags: , , , , ,

Based on previous tutorial we will try to make a business rule for user name. The simplest rule possible is that the Username must not be empty. We must be able to check for this in the BLL and, in case of error, display a message in UI. Sounds simple ? Now let’s make it.

In this case it’s a simple rule, but just imagine that for our method GetUser(…) we can have many validations (Username must be at least 5 characters, Password can’t be blank… etc) so, after checks are being done a list of errors could appear, this means we must have possibility to store all errors and make them available to the UI. For achieving this purpose we’ll create a new Class called BusinessRule in which we will store some information regarding the failed checks:

public class BusinessRule
    {
        private String _RuleType;
        public String RuleType
        {
            get { return _RuleType; }
            set { _RuleType = value;}
        }

        private String _Message;
        public String Message
        {
            get { return _Message; }
            set { _Message = value; }
        }

        private String _Property;
        public String Property
        {
            get { return _Property; }
            set { _Property = value; }
        }

        public BusinessRule()
        {
        }

        public BusinessRule(String _RuleType, String _Message, String _Property)
        {
            RuleType = _RuleType;
            Message = _Message;
            Property = _Property;
        }
    } 

We could have different type of checks which will return different type of messages: Warnings, Errors or Info. This will be stored in RuleType. The message is pretty self explanatory, the message displayed on rule fail. The property will store the property name that failed the checks (Username in our case) and will help the UI to focus the problematic controls.

Now let’s get back to the userBo class and make some changes to use the BusinessRule class.

public List<BusinessRule> BrokenRules = new List<BusinessRule>();  

        public User GetUser(string UserName)
        {

            if (string.IsNullOrEmpty(UserName))
            {
                BrokenRules.Add(new BusinessRule("Error","User name cannot be empty","UserName"));
                BrokenRules.Add(new BusinessRule("Warning", "You have 3 more retries", "UserName"));
                BrokenRules.Add(new BusinessRule("Info", "User name has a minimum length of 5 characters", "UserName"));
            }

            if (BrokenRules.Count.Equals(0))
            {
               UserDO usrDO = new UserDO();
               return  usrDO.GetUser(UserName);
            }
            else
                return null;
        }

If check fails, all the errors will be added to the BrokenRules list. This list is Public, so it can be used by the UI.

Making the UI use the BrokenRules list

Imagine that a list of BrokenRules will be available for all classes in UserBO, so we’ll need to make a window and provide a datasource to it programatically. The layout of the window will be as follow:

image

<Window x:Class="NoiaUI.Message"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Message" Height="300" Width="300" WindowStartupLocation="CenterScreen">
    <Window.Resources>
        <CollectionViewSource x:Key="MessagesSource"/>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition Height="auto"></RowDefinition>
        </Grid.RowDefinitions>
        <TextBlock Grid.Row="0" Text="Atentie" FontSize="14" Margin="5"/>
        <ListBox Name="lstMessages"  ItemsSource="{Binding Source={StaticResource MessagesSource}}" Grid.Row="1">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Image Margin="5"  Source="{Binding Path=Image}" Stretch="Fill" Width="16" Height="16"/>
                        <TextBlock Margin="5" Text="{Binding Path=Message}"/>
                    </StackPanel>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ListBox>
        <Button Name="btnContinue" Grid.Row="2" MaxWidth="100" MaxHeight="25" Click="btnContinue_Click" Margin="4">Continue</Button>

    </Grid>
</Window>

We declare a CollectionViewSource as a Window Resource that will be the ItemsSource of the listbox. Here you can see something interesting, in the ItemTemplates I added a StackPanel in which we have 2 controls, a Image and a Textbloc. To make the window better looking, will add some icons for RuleTypes, it’s much nicer to see a Error icon instead of the text “Error”.

In the cs file we take care of everything

public partial class Message : Window
    {
        public Message()
        {
            InitializeComponent();
        }

        private class MessageFormat
        {
            public BitmapImage Image { get; set; }
            public string Message { get; set; }
            public string Property { get; set; }
        }

        public void SetMessagesSource(List<BusinessRule> lstMessages)
        {
            List<MessageFormat> finalMessage = new List<MessageFormat>();
            DirectoryInfo ImageDir = new DirectoryInfo(@"..\..\Images");

            foreach (BusinessRule br in lstMessages)
            {
                FileInfo fi = new FileInfo(@"..\..\Images\"+br.RuleType+".png");
                Uri uri = new Uri(fi.FullName);
                finalMessage.Add(new MessageFormat { Image = new BitmapImage(uri), Message=br.Message, Property=br.Property });
            }

            CollectionViewSource MessagesSource = (CollectionViewSource)this.Resources["MessagesSource"];
            MessagesSource.Source = finalMessage;

        }

        private void btnContinue_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
    }

A class, MessageFormat is used to store the ruleType as BitmapImage. A public methon, SetMessageSource, is used to read the image files, add the entire content to the finalMessage list and set the CollectionViewSource source. In this way, we instantiate the windows, call the SetMessageSource method and then display it on the screen.

Let’s see how to use it in real life enviroment. In the Login window, btnLogin click event will look like this:

private void btnLogin_Click(object sender, RoutedEventArgs e)
        {

            UserBO usrbo = new UserBO();
            User usr = usrbo.GetUser(txtUserName.Text);

            if (usr == null)
            {
                if (usrbo.BrokenRules.Count.Equals(0))
                {
                    MessageBox.Show("Wrong username");
                }
                else
                {
                    Message msg = new Message();
                    msg.SetMessagesSource(usrbo.BrokenRules);
                    msg.ShowDialog();
                }
            }
            else
                MessageBox.Show("Wellcome " + txtUserName.Text);
        }

Run it, don’t type anything, just press the login button. The window should look like this:

image

The app must not allow to continue until the BrokenRules list is empty. Furthermore, based on property field in list, we could set focus to controls that failed checks. I hope you enjoyed this tutorial. Until next time, Happy coding.

And of course  the video, this time in HD 😉

Advertisements

September 17, 2009

WPF N-Tier using Entity Framework

Filed under: WPF — alinberce @ 21:35
Tags: , ,

Noia development has begin with baby steps. Right now I am trying to make a application core that will support further changes very easy. Today we are going to learn how to make layer for application and how to make them communicate. As you’ve learned so far about me I won’t give many details and explanations, the main purpose is to get the result needed as fast as possible. This being said, let’s begin our tutorial.

Let’s start by creating a new solution called Noia. In this solution we will have 4 projects as follow:

  • NoiaDAL – represents the Data Access Layer. Project type Class Library
  • NoiaBLL – represents the Business Logic Layer. Project type Class Library
  • NoiaUI – will take care of User Interface layer. Project type WPF Application
  • NoiaEF – which will contain Entities. Project type Class Library

Also, we will make a new folder NoiaDB in which we will copy the NoiaDB.sdf (SQL Server CE database).

In order to make this layers communicate, we must create the references between them:

  • In NoiaUI create reference to NoiaEF
  • In NoiaBLL create references to NoiaDAL and NoiaEF
  • In NoiaUI create references to NoiaBLL and NoiaEF

In the NoiaED we will add a new item of type Ado.Net Entity Data Model named NoiaEntityModel.edmx. When ask the Model Content we will choose Generate from database and we’ll create a new connection string pointing to the NoiaDB.sdf file. The generated connection string will look like:

metadata=res://*/NoiaEntityModel.csdl|res://*/NoiaEntityModel.ssdl|res://*/NoiaEntityModel.msl;provider=System.Data.SqlServerCe.3.5;provider connection string="Data Source=C:\Noia\NoiaDB\NoiaDB.sdf"

After the model is generated we can see all the entities created. We will rename all the be singular. I don’t want to have a object Users, I want to have a object User. Also, in properties for each entity we will rename the Entity Set Name from UserSet to Users and so on, for all the entities that require it. At the end, it should look like this:

image

What I want to achieve in this tutorial is to be able to create a login screen and check if the user name provided by UI is valid or not. The information will travel between all layers forth and back. Please remember that each layer will have it’s unique characteristics and none of the layers will overlap.

NoiaDAL (Data Access Layer)

In DAL we will need to have a class for each entity we want to use. For our particular example we will add a new class and name it UserDO (from User Data Object). In this class we must have a method to search for a user based on the user named taped by the front user. In searching for the user we will use a Linq statement. Complete class code is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NoiaEF;

namespace NoiaDAL
{
    public class UserDO
    {
        public User GetUser(string UserName)
        {
            NoiaDBEntities ne = new NoiaDBEntities();

            var usr = from u in ne.Users
                  where u.UserID == UserName
                  select u;

            return usr.FirstOrDefault();
        }
    }
}

In order to be able to use the Entities we must add a reference at the project to System.Data.Entities. This pretty much makes the job done in the DAL.

NoiaBLL (Business Logic Layer)

As in DAL, in here we will have another class for User, in this case it will be named UserBO (User business object). Because the UI layer must not access DAL directly, the BLL will be an intermediary, and after validations and checks, the BLL will decide if will ask the DAL for information or provide direct feedback to the UI if validations failed. Because validation is the scope of the next tutorial, the UserBo will only redirect the request to DAL. Again, we must add a reference at the project to System.Data.Entities.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NoiaDAL;
using NoiaEF;

namespace NoiaBLL
{
    public class UserBO
    {
        public User GetUser(string UserName)
        {
                UserDO usr = new UserDO();
                return usr.GetUser(UserName);
        }
    }
}

NoiaUI (User Interface Layer)

We will create the login window. It must contain two textboxes for user input (one for User name one for Password) and a Login button. Add a new Windows (WPF) in NoiaUI project and name it Login

<Window x:Class="Noia.Login"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Login" Width="370" Height="120" Background="#185d7c" WindowStartupLocation="CenterScreen">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>
        <Label Name="lblUserName" Grid.Row="1" Grid.Column="0" Foreground="White" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="5" >User name</Label>
        <Label Name="lblPassword" Grid.Row="2" Grid.Column="0" Foreground="White" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="5">Password</Label>
        <TextBox Name="txtUserName" Grid.Row="1" Grid.Column="1" MinWidth="200" Margin="5"></TextBox>
        <PasswordBox Name="txtPassword" Grid.Row="2" Grid.Column="1" Margin="5"></PasswordBox>
        <Button Name="btnLogin"  Click="btnLogin_Click" Grid.Row="2" Grid.Column="2" MaxWidth="50" MaxHeight="25">Login</Button>
    </Grid>
</Window>

The login button click event must communicate with the BLL and ask for data.

  private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            UserBO usrbo = new UserBO();

            User usr = usrbo.GetUser(txtUserName.Text);

            if (usr == null)
               MessageBox.Show("Wrong username");
            else
                MessageBox.Show("Wellcome " + txtUserName.Text);
        }

There are a few more things that need to be done: add a reference at the project to System.Data.Entities. Copy the App.Config file from NoiaEF to NoiaUI because we need the connection string. Set in App.xaml the startup window to login

<Application x:Class="NoiaUI.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    StartupUri="Login.xaml">
    <Application.Resources>

    </Application.Resources>
</Application>

Run it and see the result… it should work like a charm

image

Next time we shall see how to make a business rule in BLL and how to send error list from BLL to UI. It will be interesting.

P.S. Very important note: it seems that there is a problem for Linq to Entity access the SQL CE Database file with the existing SP1. In order to make things work, you must uninstall SQL CE SP1 and install this hot fix: http://support.microsoft.com/kb/958478

And the videos… as you can hear I was pretty tired when making them, so a lot of ufffs and offfs 🙂

September 11, 2009

NOIA – Planning and analyze. The beginning…

Filed under: WPF — alinberce @ 20:03
Tags: , ,

    What does NOIA stand for ? NOIA is “Not Another Invoice Application”. Pretty explanative what it should do: a application for invoices and stocks which will deal with input and output, in a small level CRM, goods stock and payments.  The reason why I mention this is because while developing it, I will make a chain of tutorials describing each important step in development. As I will learn I will share knowledge.

Technical specifications

     Because it’s not either big size or complex the platform used for development will be Visual C# 2008 Express edition. The data sources will be two, SQL Server 2008 Express Edition and SQL Server Compact Edition 3.5. Those two database systems are suitable for most cases, for small to medium clients.

Thank you Microsoft for providing a free tools to developers.

Architecture

The architecture will be layered designed, so long live the n-tier. Main goals to achieve will be:

  • Changing one layer of the system should have a minimal impact over the rest of the layers. This will help maintenance, bug fixing and unit testing. It also makes the architecture more flexible
  • Unrelated components should be loosely coupled
  • Separation between User interface, Business objects and Database

image

Each layer will be developed as follow:

– Presentation Layer: Windows Presentation Foundation (WPF) and C#

– Business Objects Layer: C#

– Data Access Layer: C# and Linq   The database will contain only a few tables needed for fresh start (like Users, Companies etc.). The rest of the tables will be added as the development progresses.

The interface

     I am planning to make a extremely user friendly interface. I give a big deal about user pleasing, this makes the app sale. Just imagine that by my design flaw, a user must lose one second each time he saves an invoice (a freaking’ message box maybe), for a number of 3000 invoices/month there will be a lose of time around 1 hour. As I am a big fan of n-tier architecture, also, I am a big fan of outlook interface. This means the interface will have a very outlookish style. Plus some other enhancements as they come along.

image

         As a friend used to say, I’ve made a map to the user so it won’t get lost. This isn’t really true, but the workflow could help and it would be easier to go to a certain operation if remembered visually. The New/Save/Delete won’t be as in the image, there will be a combo box so that the user could select company or date or stuff like this. The upper image is a WIP (Work in Progress) so it can be changed. It may seem very colored now, at the end will have a more professional look.

This was a pretty boring post, even if I tried to make it as short as possible. If you have any suggestions please send them.

Until next time we “meet”, Happy coding.

P.S. – I would like to take a moment and THANK Cristi for help, support and ideas. So, thank you man.

August 31, 2009

SQLtoCS Class Generator – an SQL Table to C Sharp class generator.

Filed under: WPF — alinberce @ 18:47
Tags: , ,

Well, I’m back and I’m bad… as someone used to say. I’m really not that bad, but, for sure I know more. Because I’ve started to work on a new project for a customer of mine I felt the need to develop a tool to help me do stuff faster. One big pressure came from the fact that I develop this app in my free time which isn’t really that much. So while eating, sleeping, rebuilding house, staying with my wife, waiting for our unborn little girl, I managed to crop some lines of code. I also finalized reading a WPF book from start till last page. And man… I must say it again: WPF Rocks!!! Tananana it rocks.

What does this app do you ask: in nontechnical words, it does what I hate do do (repeated  work) 🙂 in technical words it creates two classes for an Sql Server table. I’ve always been a fan of nTier architecture and the way WPF and C# works it this concept pleases me. And in big lines, this program does the business layer (Business objects) of a nTier architecture. Or at least, this is what I like to think it does.

Here is a screenshot:

Capture

The classes are generated in a few seconds. Just enter the credentials for the SQL Server or SQL CE connection, select Database and the table and press the Generate button. There are a few customizable parameters: class name, collection name and the namespace. The cs classes are saved in the exe’s directory.

The program detects what keys (PK and FK) are contained by the table and generates methods based on them.There are a lot of tools that do this on the net.  I’ve tested quite a few. There was always something bothering me and this is the main reason I started doing one for myself.

Please take your time and test it. If you have suggestions, please sent it to me.

UPDATE: The application can be downloaded from here: SqlToCs

A short, bad quality Youtube presentation:

Ah,  and about that PayPal button.. hehe… Donations are never required but they are more than welcomed.

June 5, 2009

WPF Localization – Do you speak English ? Sprechen Sie Deutsch? 你讲中文?

Filed under: WPF — alinberce @ 19:59
Tags: , , ,

    By using localization, you allow controls in a application to change their content (particularly text labels and images) according to user preferences or according to current culture settings of the Windows operating system. In WPF unit of localization is in the XAML file (the compiled BAML resource). This means that for every language supported by the application you will have a BAML resource.

Let’s begin by creating a new WPF Application named WpfLocalization. In it we will add two buttons and a text block each with it’s English text. The Windows1.xaml file will look like this:

<Window x:Class="WpfLocalization.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <StackPanel>
        <Button  Margin="30" Name="button1">Save</Button>
        <Button  Margin="30" Name="button2">Cancel</Button>
        <TextBlock Margin="30">Item saved succesfully</TextBlock>
    </StackPanel>
</Window>

As you can notice, I’ve already started to create the English version of the application.

First thing we need to do is add localization support for our project. To do this, just open the WpfLocalization.csproj file and add the following line

<UICulture>en-US</UICulture>

in the <PropertyGroup> section of the file. Reload the project and let’s continue. We need also to set the NeutralResourceLanguage assembly attribute. The simplest way to do this is open the AssemblyInfo.cs file in the Properties Folder and uncomment the following line:

[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]

By setting this we tell the CRL loader how to find the correct resource DLL for the selected culture. If it can’t find the indicated culture he will use the neutral one.Run the application and go to the Debug folder. In there we have the exe file and a folder en-US which contains the US culture resource DLL.

All the controls that need to be localized must have the Uid attribute. This means that we must modify in our .xaml files, all the controls. Pretty awful stuff to do manually. But we are lucky, Microsoft thought of this and helps us by offering the msbuild tool that will do the job automatically for us.

Start a command prompt and go to the following path: C:\Windows\Microsoft.net\Framwork\v3.5 in here is the msbuild.exe which we will use.

Run the following command:

msbuild /t:updateuit C:\WpfLocalization\WpfLocalization.csproj

The result should look like this:

image

And if you reload the project, in window1.xaml the stack panel is updated and it should have the Uid attribute for it’s elements.

<StackPanel x:Uid="StackPanel_1">
        <Button x:Uid="button1" Margin="30" Name="button1">Save</Button>
        <Button x:Uid="button2" Margin="30" Name="button2">Cancel</Button>
        <TextBlock x:Uid="TextBlock_1" Margin="30"> The item was saved succesfully</TextBlock>
    </StackPanel>

If you think that this was hard to do, wait to see what’s coming. Now we must extract the resources as a .csv file and translate the text as wanted. To do this we will use the Locbaml.exe tool. Copy the LocBaml.exe to bin\Debug\en-US folder of the project. Also copy the executable file WpfLocalized.exe to the same folder. Open a command prompt and go to the en-US folder and run the following command.

Locbaml /parse WPFLocalization.resources.dll /out:translate.csv

The result of this command will be the creation of a translate.csv file. Open this file and replace the English words with the German translation:

  • Save -> Sichern
  • Cancel -> Abbrechen
  • The item was saved succesfully! -> Posten erfolgreich gespeichert

After the translation is done, we need to generate the localized satellite DLL file and install it. Create a sister directory to en-US and name it de-DE. To do this we need to use the Locbaml file again. Open a command window and navigate to the folder where translate.csv is. Run the command:

Locbaml /generate /trans:translate.csv /out:..\de-DE /cul:de-DE WpfLocalization.resources.dll

We managed to complete the localization of the code. The result isn’t visible yet. Because we don’t want to change the Windows region settings to see the localized version, we will programmatically make the switch in the app.xaml.cs file.

public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            //string sCulture = "de-DE";
            string sCulture = "en-US";
            System.Threading.Thread.CurrentThread.CurrentUICulture =
                new System.Globalization.CultureInfo(sCulture);
            System.Threading.Thread.CurrentThread.CurrentCulture =
                new System.Globalization.CultureInfo(sCulture);
            base.OnStartup(e);
        }    
    }

Final result is encouraging :)  Happy coding.

image image

The video lesson: (sorry about the video, it’s quality is absolutely horrible, I uploaded at high quality but it looks really rubish)

 

May 28, 2009

WPF – the almighty Button Tooltip

Filed under: Uncategorized — alinberce @ 20:28
Tags: , ,

A very brief tutorial about making a Button Tooltip that contains not just text, but images too. WFP Rocks!

May 27, 2009

WPF Lesson One – Layouts (The beginning)

Filed under: Uncategorized — alinberce @ 16:25
Tags: , ,

(as usual, videos are at the bottom of the post)

Hello. I decided to make a turn on my learning curve, so I decided to switch to WPF – XAML… Funny name it sounds like “zama”, a word that means some sort of food in my native language.

Because I’m a beginner, I will start, of course, with the basics.

What I can say about WPF is that it represents a pretty dramatic change in the way I approach user interfaces. In first version of .NET controls where fixed using hard coded coordinates (Top, Left). So… not a really "changeable" interface. The only things that saved the day were anchoring and docking properties. In the second .NET
we had FlowLayoutPanel and TableLayoutPanel. By using this, the interface became more flexible and more web-like.
WPF introduces a new layout system in which coordinates are placed on a second place and flow layouts becomes the winner. This gives us the possibility to create flexible interfaces which aren’t that dependent on resolution or size.

The main idea beneath the WPF window is that it can contain only one element. First thing that comes to my mind is: How I’ll do all the complex interfaces I think of if the window can hold only one element. Answer is simple: just place a container in the windows… and add all the elements in that container.

The  WPF layout containers are panels and can be:

  • StackPanel – Places elements in a horizontal or vertical stack.
  • WrapPanel – Places elements in a series of wrapped lines.
  • DockPanel – Aligns elements against an entire edge of the container.
  • Grid – Arranges elements in rows and columns according to an invisible table.

All this new names and properties may sound wired to you… it did sounded wired when I first read about them, but we’ll take it step by step and in the end, everything will be clear as daylight.

Let’s begin by creating a new Project of type Wpf Application, named WPFLesson1. By default Visual Studio creates a new window called Window1.xaml. Because the Grid panel is the almighty one, it is added by default.

 

<Window x:Class="WPFLesson1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid>
        
    </Grid>
</Window>

The StackPanel – For the beginning I will start with the StackPanel. Delete the <Grid></Grid> and add a StackPanel with one label and three buttons in it.

<Window x:Class="WPFLesson1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <StackPanel>
        <Label>Hello... This is StackPanel Label</Label>
        <Button>First Button </Button>
        <Button>Second Button </Button>
        <Button>Third Button </Button>
    </StackPanel>
</Window>

Run the project and it should look like this:

1

Without adding any code, the label and buttons were arranged from the top to the bottom. All these elements are stretched to full width of the panel, and their height is automatically set to be enough to display the text inside them.

If I want items to be displayed Horizontally, then all I must do is modify the <StackPanel> to this:

 <StackPanel Orientation="Horizontal">

Run the project and see if it looks like this:

2

As can be seen, the Height of element’s height are stretched to panel’s weight, and their width is set to accommodate the text.

Let’s revert on how was before and try to make some alignment. We’ll make the label on the Left, First button on the center and last button on the right. To do this, we’ll use the HorizontalAlignament of the elements.

<StackPanel>
        <Label HorizontalAlignment="Left">Hello... This is StackPanel Label</Label>
        <Button HorizontalAlignment="Center">First Button </Button>
        <Button>Second Button </Button>
        <Button HorizontalAlignment="Right">Third Button </Button>
    </StackPanel>

3

Well, well, well as you can see the result is as intended, but important thing: no more stretch for the elements we aligned.

There are two more important things for me to tell you: margins and Minimum/Maximum sizes. If I want some space between a control and the controls around it, I use the Margin property. Setting explicit sizes for a control in WFP is not really recommended, but setting a range of size for it, is recommended.

 <StackPanel>
        <Label Margin="5" MaxWidth="400" HorizontalAlignment="Left">Hello... This is StackPanel Label</Label>
        <Button Margin="5" MaxWidth="400" HorizontalAlignment="Center">First Button </Button>
        <Button Margin="5" MaxWidth="200" >Second Button </Button>
        <Button Margin="5" MaxWidth="400" HorizontalAlignment="Right">Third Button </Button>
    </StackPanel>

4

The WrapPanel – arranges controls in the available space, one line or column at a time.

<WrapPanel>
        <Label Margin="5" MaxWidth="400" HorizontalAlignment="Left">Hello... This is StackPanel Label</Label>
        <Button Margin="5" MaxWidth="400" HorizontalAlignment="Center">First Button </Button>
        <Button Margin="5" MaxWidth="200" >Second Button </Button>
        <Button Margin="5" MaxWidth="400" HorizontalAlignment="Right">Third Button </Button>
    </WrapPanel>

5

Resize it to see how the WrapPanel does it’s job.

The DockPanel – do you want controls stretched on one side of a panel ? Don’t worry, DockPanel is here.

    <DockPanel>
        <Label DockPanel.Dock="Top" Margin="5" MaxWidth="400" HorizontalAlignment="Left">Hello... This is StackPanel Label</Label>
        <Button DockPanel.Dock="Left" Margin="5" MaxWidth="400" HorizontalAlignment="Center">First Button </Button>
        <Button DockPanel.Dock="Bottom" Margin="5" MaxWidth="200" >Second Button </Button>
        <Button DockPanel.Dock="Right" Margin="5" MaxWidth="400" HorizontalAlignment="Right">Third Button </Button>
    </DockPanel>

6

The Grid – the grid panel separates elements into a grid of rows and columns. With it we can do pretty much all that we can do with previous explained panels. Using this panel implies two steps: first chose the numbers of rows and columns, second assign each element to the appropriate row and column. Grid lines are invisible, but I will enable it for our lesson.

<Grid ShowGridLines="True">
           <Grid.RowDefinitions>
                <RowDefinition></RowDefinition>
                <RowDefinition></RowDefinition>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition></ColumnDefinition>
                <ColumnDefinition></ColumnDefinition>
                <ColumnDefinition></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <Label  Grid.Row="0" Grid.Column="0" Margin="5" MaxWidth="400" HorizontalAlignment="Left">Hello... </Label>
            <Button  Grid.Row="1" Grid.Column="0" Margin="5" MaxWidth="400" HorizontalAlignment="Center">First Button </Button>
            <Button   Grid.Row="0" Grid.Column="3" Margin="5" MaxWidth="200" >Second Button </Button>
            <Button  Grid.Row="1" Grid.Column="1" Margin="5" MaxWidth="400" HorizontalAlignment="Right">Third Button </Button>
    </Grid>

7

As you may think already, these panels won’t be used alone. To develop ergonomic user friendly interfaces these panels must be combined. So we’ll start to use our knowledge to create something useful: a classic text edit window. Not only that we will have it done, but we’ll do it in 2 ways. And I’m sure that there are some more ways to do it. (As someone said: each thing in a program can be done in at least 4-5 different ways).

First attempt: using a DockPanel and a StockPanel

The windows will have the following format: a big textbox at the top and two buttons at the bottom for Save and Cancel. For the buttons we’ll use a StockPanel. This panel will be put inside of a DockPanel at the bottom side of it. Set LastChildFill to true, so you can use the rest of the windows to fill in another content.

    <DockPanel LastChildFill="True">
        <StackPanel DockPanel.Dock="Bottom" HorizontalAlignment="Center" Orientation="Horizontal">
            <Button Margin="8,8,4,8" Padding="3">Save</Button>
            <Button Margin="4,8,8,8" Padding="3">Cancel</Button>
        </StackPanel>
        <TextBox DockPanel.Dock="Top" Margin="10">Write some text in here.</TextBox>
    </DockPanel>

Run the project and see what happens

8

Was this easy or what ? But what if I tell you that this can be done even easier ?  What ?  You don’t believe me ?

Second attempt: the mighty Grid Panel

    <Grid ShowGridLines="True">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>
        <TextBox Margin="10" Grid.Row="0">Write some text in here.</TextBox>
        <StackPanel Grid.Row="1" HorizontalAlignment="Center" Orientation="Horizontal">
            <Button Margin="10,10,2,10" Padding="3">Save</Button>
            <Button Margin="2,10,10,10" Padding="3">Cancel</Button>
        </StackPanel>
    </Grid>

9

Pretty easy, huh ?  I told you so…

And we came to the end of a very nice lesson. We’ve learn about WPF layouts what they are and how we use them. A very good book for learning is :”Pro WPF in C# 2008” by Matthew MacDonald

I really hope that I’ve been helpful. So, until next time: Happy coding!

Because of the restricted length in youtube videos of 10 minutes, today you’ll have 2 parts