Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C# (http://www.go4expert.com/articles/c-sharp-tutorials/)
-   -   Formatting WPF Controls (http://www.go4expert.com/articles/formatting-wpf-controls-t30096/)

shabbir 12May2014 11:31

Formatting WPF Controls
 
A WPF Window is integration of multiple elements. Top level elements such as Window, layout containers such as StackPanel, DockPanel, Grid etc. and control elements such as text boxes, buttons, menu bars and tool bars etc. All the control elements in WPF derive from System.Windows.Control base class. Control elements have some common properties which have been packaged in the Control base class. In this article, the WPF base Control class has been explained in detail along with its certain features and important characteristics.

Setting Control Colors



All the controls that inherit from the Control base class have Background and Foreground properties that can be used to set the respective colors of the control. Usually background color is considered as the background surface of a control and foreground color is the color of the text of the control. You might be thinking that the Background and Foreground properties would use Color object. However, in WPF, things are bit more interesting. Background and Foreground properties of controls use Brush objects. This allows developers to enhance the GUI of their controls by using SolidColorBrushe and LinearGradientBrushe etc. To see, the Background and Foreground color properties of Control class in action, have a look at the first tutorial of this example.

Note: If you are totally new to WPF, you might not be able to comprehend the concepts discussed in this article, right away. I have written this tutorial for absolute beginners which I would recommend you to look at and then you can carry on with this tutorial.

Example1

Edit the front end XAML file of your application and it should look like this:
Code:

<Window x:Class="WPFTutorial.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="200" Width="400" MinWidth="150">

    <Grid >
        <Grid.RowDefinitions>
            <RowDefinition ></RowDefinition>
        </Grid.RowDefinitions>
       
        <Grid.ColumnDefinitions>
            <ColumnDefinition  ></ColumnDefinition>
            <ColumnDefinition  ></ColumnDefinition>
        </Grid.ColumnDefinitions>
     
        <Button Name="topleft" Grid.Row="0" Grid.Column="0"> Top Left Button</Button>
        <Button Name="topright" Grid.Row="0" Grid.Column="1">Top Right Button</Button>
    </Grid>
</Window>

Here, in the above code, A Grid layout with one row and two columns has been declared. In the first column, a Button control named ‘topleft’ has been added and in the second column, a button named “topright” has been added.

In the constructor of the code behind MainWindow.xaml.cs class make changes as follows:
Code:

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            topleft.Background = new SolidColorBrush(Colors.Aqua);
            topright.Background = new LinearGradientBrush(Colors.Black, Colors.White,90);
        }
 
    }

In the code behind file in the constructor, the Background property of the control named top left has been set. A new instance of the SolidColorBrush has been created and a Static property Aqua of the color class has been passed to. This would set the background color of the topleft button to “Aqua”.

Similarly, the background property of the control named “topright” has been set to a LinearGradientBrush which receives three arguments: the starting color of the gradient, the end color of the gradient and the angle. The 0 angle means a horizontal gradient, 90 means a vertical gradient. The output of the code shown in Example1 is as follows:

Output1

http://imgs.g4estatic.com/c-sharp/wp...l/Example1.png

Setting Background Colors via XAML code



Apart from setting the Background property in the code, it can also be set through the front end XAML file using the attached properties. This is shown in the following Example:

Example2
Code:

<Window x:Class="WPFTutorial.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="200" Width="400" MinWidth="150">

    <Grid >
        <Grid.RowDefinitions>
            <RowDefinition ></RowDefinition>
        </Grid.RowDefinitions>
       
        <Grid.ColumnDefinitions>
            <ColumnDefinition  ></ColumnDefinition>
            <ColumnDefinition  ></ColumnDefinition>
        </Grid.ColumnDefinitions>
     
        <Button Name="topleft" Grid.Row="0" Grid.Column="0">
            Top Left Button
            <Button.Background>
                <SolidColorBrush Color="Aqua"/>
            </Button.Background>
        </Button>
        <Button Name="topright" Grid.Row="0" Grid.Column="1">
            Top Right Button
            <Button.Background>
                <LinearGradientBrush StartPoint="0, 0" EndPoint="0,1">
                    <GradientStop Color="Black" Offset="0.0" />
                    <GradientStop Color="White" Offset="1" />
              </LinearGradientBrush>
            </Button.Background>
        </Button>
    </Grid>
</Window>

Here the topleft button’s background property has been set via this line of code:
Code:

            <Button.Background>
                <SolidColorBrush Color="Aqua"/>
            </Button.Background>

Setting LinearGradientBrush of the topright button has been done in the following line of code:
Code:

            <Button.Background>
                <LinearGradientBrush StartPoint="0, 0" EndPoint="0,1">
                    <GradientStop Color="Black" Offset="0.0" />
                    <GradientStop Color="White" Offset="1" />
              </LinearGradientBrush>
            </Button.Background>

Here the StartPoint refers to the Starting coordinates where you want to start the gradient. The EndPoint refers to the end point of the gradient. The Offset refers to the starting position of the color from where gradient has to start. For instance if in the above code the Offset attribute of black color is set to 0.5, the Black to White gradient starts appearing after half of the vertical height of the control. The output of this Example is similar to the Example1:

Output2

http://imgs.g4estatic.com/c-sharp/wp...l/Example2.png

There is a short hand XAML notation for defining SolidColorBrush. For instance, the Background color of button can also be set via this short hand method:
Code:

      <Button Background="Aqua" Name="topleft" Grid.Row="0" Grid.Column="0">
            Top Left Button
        </Button>

In the above case, Background attribute of the button control has been set to Aqua. However, for LinearGradientBrush, the technique described in Example1 and Example2 has to be used.

Apart from using properties from the Static Colors class, RGB values can also be used to set the background and foreground colors of any control. For instance, the following line of code can also be used to set the background color of a Button Control:
Code:

<Button Background="#00FF00">A Button</Button>
The above line of code will set the background color of the button to Green. To specify RGB values in XAML code, the value should start from #, the first two number represent the value of red which is denoted in hexadecimal notation where 00 means none and FF means 255. The RGB stands for Red Green & Blue and their value ranges from 0 to 255. In the above code, value for red is 0, value for green is FF means 255 and value for Blue is again 00. This means that the background of the button should be purely green.

The procedure for setting foreground colors is exactly identical to that of setting the background color as explained in Example1 and Example2.

Setting Control Font Properties



Apart from setting Background and Foreground colors of the controls, the Control base class also includes set of properties that can be used to manipulate fonts of the texts on the controls. Following are some of the most widely used Font properties for the WPF controls:
  • FontFamily: It specifies the family of the font such Cambria, Ariel, Times New Roman etc.
  • FontSize: This is used to set the size of the text fonts.
  • FontStyle: Such as Italic, Normal.
  • FontWeight: Used to describe if the text is Bold, Light, Heavy or ExtraBold.
To see above font properties in action, have a look at the third example of this article:

Example3:
Code:

<Window x:Class="WPFTutorial.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="200" Width="400" MinWidth="150">

    <Grid >
        <Grid.RowDefinitions>
            <RowDefinition ></RowDefinition>
        </Grid.RowDefinitions>
       
        <Grid.ColumnDefinitions>
            <ColumnDefinition  ></ColumnDefinition>
            <ColumnDefinition  ></ColumnDefinition>
        </Grid.ColumnDefinitions>
     
        <Button FontStyle="Italic" FontFamily="Cambria" FontWeight="ExtraBold"
                FontSize="16" FontStretch="UltraExpanded" Background="Aqua" Name="topleft"
                Grid.Row="0" Grid.Column="0">
            Top Left Button
        </Button>
        <Button Name="topright" Grid.Row="0" Grid.Column="1">
            Top Right Button
            <Button.Background>
                <LinearGradientBrush StartPoint="0, 0" EndPoint="0,1">
                    <GradientStop Color="Black" Offset="0" />
                    <GradientStop Color="White" Offset="1" />
              </LinearGradientBrush>
            </Button.Background>
        </Button>
    </Grid>
</Window>

The code in Example3 is similar to the one in Example1 and Example2 but here in this case, the font properties of the topleft button have been altered. FontStyle has been set to italic, FontFamily to Cambria, FontWeight to ExtraBold, FontSize to 16 and FontStretch to UltraExpanded. The output window of the above XAML code is as follows:

Output3

http://imgs.g4estatic.com/c-sharp/wp...l/Example3.png

Setting Text Decorations



TextDecoration property allows underlining, strike through, baseline and over line the text on the control. In the fourth example of this tutorial, the TextDecoration property of the Control class has been implemented. Have a look at it:

Example4:
Code:

<Window x:Class="WPFTutorial.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="200" Width="400" MinWidth="150">

    <Grid >
        <Grid.RowDefinitions>
            <RowDefinition ></RowDefinition>
            <RowDefinition ></RowDefinition>
        </Grid.RowDefinitions>
       
        <Grid.ColumnDefinitions>
            <ColumnDefinition  ></ColumnDefinition>
            <ColumnDefinition  ></ColumnDefinition>
        </Grid.ColumnDefinitions>
     
        <TextBlock TextDecorations="Underline"  Name="topleft"
                Grid.Row="0" Grid.Column="0">
            Top Left Text Box
        </TextBlock>

        <TextBlock TextDecorations="StrikeThrough" Name="topRight"
                Grid.Row="0" Grid.Column="1">
            Top Right text box
        </TextBlock>

        <TextBlock  TextDecorations="Overline"  Name="bottomleft"
                Grid.Row="1" Grid.Column="0">
          Bottom Left Text Box
        </TextBlock>

        <TextBlock TextDecorations="Baseline"  Name="bottomright"
                Grid.Row="1" Grid.Column="1">
          Bottom Right Text Box
        </TextBlock>
    </Grid>
</Window>

In the above code, there is a Grid having two rows and two columns and each cell contains one TextBlock. The TextBlock with name topleft has a TextDecoration value of Underline, the TextBlock topright has aTextDecoration value of StrikeThrough, TextBlock bottomright has aTextDecoration value of Overline and the last TextBlock’s TextDecoration property has a value of Baseline. The output of the XAML in Example4 is as follows:

Output4

http://imgs.g4estatic.com/c-sharp/wp...l/Example4.png

A very important point to note here is that not all controls contain this TextDecoration property. For instance if the Button control is used, this TextDecoration property cannot be used with that control.

Setting Mouse Cursors on Controls



Another important property contained by the Control base class is the Cursor property that is used to set the cursor’s shape when it is hovered on a particular control. The Cursor property has several values depending on which the shape of the cursor is changed when it is hovered over that particular control. This concept has been explained in the fifth example of this tutorial:

Example5
Code:

<Window x:Class="WPFTutorial.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="200" Width="400" MinWidth="150">

    <Grid >
        <Grid.RowDefinitions>
            <RowDefinition ></RowDefinition>
         
        </Grid.RowDefinitions>
       
        <Grid.ColumnDefinitions>
            <ColumnDefinition  ></ColumnDefinition>
            <ColumnDefinition  ></ColumnDefinition>
        </Grid.ColumnDefinitions>
     
        <Button Cursor="Hand"
                Name="topleft"
                Grid.Row="0" Grid.Column="0">
            Left Button
        </Button>

        <Button Cursor="Cross" Name="topRight"
                Grid.Row="0" Grid.Column="1">
            Right Button
        </Button>
    </Grid>
</Window>

In the above example, a grid contains two buttons. The cursor property of the topleft button has been set to Hand and the cursor property of the topright button has been set to Cross. Now if the above code is compiled, the corresponding window will have two buttons as showing in the output:

Output5

http://imgs.g4estatic.com/c-sharp/wp...l/Example5.png

The mouse is hovered on the left button in the above window; cursor will change to a hand shape. Similar if cursor is hovered on the right button in the above window, a cross will appear on that button control. In the last example, only two cursor values were used, however you can you other cursor values as well to render a more realistic user experience.

A very interesting situation arises when a parent control’s Cursor property is set to some value and the child control have a different value for its Cursor property. For instance imagine scenario where a Parent window’s Cursor property is set to Help and a Button in that window has a Cursor property of Hand or Cross, what will help in such cases?

The answer is that the child control’s value of Cursor property overrides the Parent control’s cursor property; therefore all the control on window where Cursor property is not specified will adopt the cursor property of the parent control. And those child controls where Cursor property has been specifically mentioned, will adopt that Cursor property. This concept has been explained in the next example.

Example6
Code:

<Window Cursor="Help" x:Class="WPFTutorial.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="200" Width="400" MinWidth="150">

    <Grid >
        <Grid.RowDefinitions>
            <RowDefinition ></RowDefinition>
        </Grid.RowDefinitions>
       
        <Grid.ColumnDefinitions>
            <ColumnDefinition  ></ColumnDefinition>
            <ColumnDefinition  ></ColumnDefinition>
            <ColumnDefinition  ></ColumnDefinition>
        </Grid.ColumnDefinitions>
     
        <Button Cursor="Hand"
                Name="button1"
                Grid.Row="0" Grid.Column="0">
          Button1
        </Button>

        <Button Name="button2"
                Grid.Row="0" Grid.Column="1">
            Button2
        </Button>

        <Button Name="button3"
                Grid.Row="0" Grid.Column="2">
            Button3
        </Button>
    </Grid>
</Window>

In the above Example, the Cursor property of the top level Window element has been set to Help. This means that all the controls inside this Window will have this Cursor property except those controls which explicitly override the Parent control’s cursor property.

In the code above, the Window contains a Grid layout having one row and three columns. Each column contains one Button control in it. The Cursor property of the first button is set to “Hand” while the Cursor property of the remaining two buttons has not been set. The output window looks like this:

Output6

http://imgs.g4estatic.com/c-sharp/wp...l/Example6.png

In the above window if the mouse is hovered on Button1, a Hand will appear and if mouse is hovered over the remaining two buttons on the right, Help cursor will appear since they don’t have their own Cursor property and they will use the default Cursor property of the container in which they have been placed.

The Control class is inherited by all the controls elements in WPF. I would advise you to further explore it and understand the underlying concepts class. All the controls that you would use in your WPF applications would share many common properties as discussed in this tutorial. For more interesting WPF articles, keep visiting this website.


All times are GMT +5.5. The time now is 00:24.