Tuesday, February 5, 2013

The Basics: Intro to Windows Presentation Foundation

I have spoken to several developers this week who have heard of WPF, but have no experience with it. I have been working with this technology for so long, that I take it for granted. I decided to write a few blog posts specifically for those developers that are just starting out with WPF.
The Links First, here are a few useful links to get you started
http://www.microsoft.com/expression/
download Microsoft Expression Blend
http://www.microsoft.com/visualstudio/eng/products/visual-studio-overview 
go to express products to download the free version of Visual Studio
This is by far the Best book for learning WPF. I highly recommend it

Introduction Now that I've used the term WPF several times, I should probably give a formal definition for it. As seen in the title of this blog post, WPF stands for Windows Presentation Foundation. So why use WPF when there are other options like Windows Forms out there? While there are many opinions out there, I believe the biggest benefit to using WPF is that it provides a clear separation between the application behavior and the user interface. Rather than defining the user interface in code like VB or C#, WPF introduces xaml (eXtensible Application Markup Language). This xml markup is used to define the user interface. When an application is built, the compiler reads the xaml (pronounced zammel) markup and generates the appropriate objects to construct the user interface.
Everything you can do in xaml you can do in code. You can create a WPF application without writing a single line of xaml, but that is not common. Declaring your user interface in xaml provides a cleaner separation between the look of the application and the behavior of the application. It also allows you to use the design tools (like Expression Blend) available for creating complex user interfaces. Also, xaml is much easier to read and a lot shorter than code.
C# / Xaml Comparison
The following xaml and c# code both produce the same result – the following interface.
image
xaml
    <Grid>        
        <StackPanel>
            <Label Content="My First WPF App"/>
            <Button Content="Hello World"/>
            <TextBox/>            
        </StackPanel>
    </Grid>

C#
            Grid g = new Grid();
            StackPanel s = new StackPanel();

            Label l = new Label();
            l.Content = "My First WPF App";

            Button b = new Button();
            b.Content = "Hello World";

            TextBox t = new TextBox();

            //populate stack panel
            s.Children.Add(l);
            s.Children.Add(b);
            s.Children.Add(t);            

            //add stackpanel to grid
            g.Children.Add(s);

            //set application content
            this.Content = g;

From this small example you can clearly see that the C# code is much longer and more difficult to read than the equivalent xaml markup.

Xaml Basics

To initialize an object simply create a new xml element.

             <StackPanel/>
        <
Button
/>
        <
Label
/>
        <
TextBlock
/>
        <
TextBox
/>
        <
ListBox/>
 
         . . .
   
There are two ways of adding properties to elements:

1)Inline
             <StackPanel Orientation="Horizontal" Margin="2"/>   
        <
Button Content="Click Me" Height="50" Width
="100"/>
        <
Label Content
="Hi"/>
        <
TextBox Text
="Enter text here"/>
        <
ListBox Height="300"/>


or

2) As nested elements. This allows building more complex elements.
        <Button Height="50" Width="100">
            <StackPanel Orientation="Horizontal">
                <Label Content="Click"/>
                <Image Source="click_here.png"/>
            </StackPanel>
        </Button>


The Visual Tree
WPF introduces the notion of a visual tree and a logical tree. It is important to understand the difference between the two.

When building a user interface, one can talk about the different elements that make up the interface. That is what is referred to as the logical tree.

    <Grid>
        <Button/>
    </Grid>

The logical tree for this code is represented as
image

The visual tree refers to the various visual elements that make up a logical element. The logical tree just for the button above is represented as:

image

This specifies, in great detail, how the button control is visually constructed. WPF gives developers the flexibility to completely redefine visual tree of any given control. This is done via Styles and Templates.

Styles and Templates
Here is where WPF development, in my opinion, really shines. Styles can be used to make reusable chunks of code that define visual properties of specific UI elements or a certain type of element. They are very similar to Cascading Style Sheets in web development. With styles, you can easily define the look for all the buttons within a given application as a single style and apply it globally.style

Below I define 4 styles for Label controls. The first is the default style for all labels within scope. If a label is created within the scope of this style and no style is defined, it will pick up the properties defined by this style. Default styles are created in WPF by simply creating a style without giving it a Key (style identifier).

                <Style TargetType="{x:Type Label}">
                    <Style.Setters>
                        <Setter Property="Foreground" Value="Red"/>
                        <Setter Property="FontWeight" Value="Bold"/>
                        <Setter Property="FontSize" Value="40"/>
                    </Style.Setters>
                </Style>

                <Style TargetType="{x:Type Label}" x:Key="BigBlueStyle">
                    <Style.Setters>
                        <Setter Property="Foreground" Value="Blue"/>
                        <Setter Property="FontWeight" Value="Bold"/>
                        <Setter Property="FontSize" Value="40"/>
                    </Style.Setters>
                </Style>

                <Style TargetType="{x:Type Label}" x:Key="LittleGreenStyle">
                    <Style.Setters>
                        <Setter Property="Foreground" Value="Green"/>
                        <Setter Property="FontWeight" Value="Bold"/>
                        <Setter Property="FontSize" Value="10"/>
                    </Style.Setters>
                </Style>


The second and third styles both have Keys. In order to use this style, the label must set the Style attribute using the following syntax.

        <StackPanel>
            <Label Content="First Label"/>
            <Label Content="Second Label" Style="{DynamicResource BigBlueStyle}"/>
            <Label Content="Third Label" Style="{DynamicResource LittleGreenStyle}"/>
            <Label Content="Fourth Label" Foreground="Purple"/>
        </StackPanel>

The product of this code looks like this:

image

Notice how the fourth label overrides the foreground color to purple.

Templates are a bit different from styles. While styles allow you to set properties, templates allow you to redefine the visual tree of an element. There are two different kinds of templates used in WPF

1)Datatemplate – Used for describing how data should be displayed. This type of template is commonly used in list-based controls like listboxes or comboboxes.

2)ControlTemplate – Used for describing the appearance of a control.

Simple example:

In this example I change the visual tree of the button. This defines the button to be made up of a green grid with an inner stackpanel that has a textblock, a rectangle and a combobox. Note, the user can still interact with any of the elements inside the button like the combobox. This, in my opinion, is the single most powerful feature in WPF. Developers are completely free to redefine visual elements in inumerable ways to meet their needs.

       <Button Height="100" Width="200">
            <Button.Template>
                <ControlTemplate>
                    <Grid Background="Green">
                        <StackPanel  VerticalAlignment="Center"> 
                            <TextBlock Text="Click Me"/>
                            <Rectangle Fill="Black" Height="30" />
                            <ComboBox>
                                <ComboBox.Items>
                                    <ComboBoxItem Content="Item One"/>
                                    <ComboBoxItem Content="Item Two"/>
                                    <ComboBoxItem Content="Item Three"/>
                                </ComboBox.Items>
                            </ComboBox>
                        </StackPanel>                        
                    </Grid>
                </ControlTemplate>
            </Button.Template>
        </Button>
imageimage

This has only been a quick intro to WPF. I hope it’s been helpful to understand the basics of this technology. Please take a look around this blog to find other articles related to wpf development.

Happy Coding!

No comments:

Post a Comment