14. Overview of WPF

About this Tutorial

Objectives

Delegates will learn to develop applications using C# 4.5. After completing this course, delegates will be able to:

  • Use Visual Studio 2012 effectively
  • Create commercial C# Web Applications
  • Develop multi-threaded applications, Use WCF and LINQ

Audience

This course has been designed primarily for programmers new to the .Net development platform. Delegates experience solely in Windows application development or earlier versions of C# will also find the content beneficial.

Prerequisites

No previous experience in C# programming is required. But any experience you do have in programming will help. Also no experience in Visual Studio is required. But again any experience you do have with programming development environments will be a valuable.

Download Solutions

HTML tutorial


Overview

  1. WPF is Microsoft’s new API for creating desktop apps
    • Utilizes the high-performance DirectX engine.
    • Much richer interfaces than possible in Windows Forms UIs.
  2. Primary features of WPF:
    • Web-like layout model.
    • Rich drawing model for 2-D and 3-D graphics.
    • Rich text model.
    • Animation support
    • Support for audio and video media.
    • Styles and templates.
    • Commands.
    • XAML-based declarative UI.
    • Interop with Windows Forms controls.
  3. WPF Application Types:
    • Standalone applications
      HeaderContentControl
    • XAML browser applications
      XBAApp
  4. WPF User Interfaces and XAML:
    • You will typically create WPF UIs using XAML:
      • Extensible Application Markup Language
      • A declarative syntax for creating objects, and for setting properties and eventhandlers
      • This XAML will create this UI
        <Window ... >
         ...
         <Label>Label</Label>
         <TextBox>TextBox</TextBox>
         <RichTextBox .../>
         <RadioButton>RadioButton</RadioButton>
         <CheckBox>CheckBox</CheckBox>
         <Button>Button</Button>
        </Window>
      • XAMLExample

  5. WPF Class Hierarchy
    ClassHierarchy

Estimated Time – 1 Hour

Not what you are looking? Try the next tutorial – Overview of WCF

Lab 1: Creating WPF Applications

Lab 1: Creating WPF Applications
  1. Anatomy of a WPF Standalone Application – Create a new WPF application via a file or new project. The application – .xaml file defines the application; .xaml.cs file is the code-behind file, contains application event-handlers. A Window – .xaml file defines a Window; .xaml.cs file is the code-behind file, contains window event-handlers –
    Anatomy
  2. XAML Application Code
    <Application
     xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
     x:Class="WpfApplication1.App"
     StartupUri="MainWindow.xaml">
     <Application.Resources>
     </Application.Resources>
    </Application>

    C# Application Code
    namespace WpfApplication1
    {
     public partial class App : Application
     {
     }
    }
  3. View code file.
  4. View code file.
  5. XAML Window Code
    <Window x:Class="WpfApplication1.MainWindow"
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
    </Grid>
    </Window>

    C# Window Code
    namespace WpfApplication1
    {
      public partial class MainWindow : Window
        {
        public MainWindow()
        {
          InitializeComponent();
        }
      }
    }
  6. View code file.
  7. View code file.
  8. Adding Controls to a Window:
    • Add controls to a window:
      • Either add tags to the XAML (manually or from the Toolbox).
      • Or write C# code to create components programmatically.
    • XAML is usually the preferred option
      • XAML element names (e.g. TextBox) correspond to a WPF class.
      • Each XAML element creates a new instance of that class.
        <Window ...>
         <Grid>
          <TextBox Name="textBox1" .../>
          <Button Name="button1">Button</Button>
          <Label Name="label1">Label</Label>
         </Grid>
        </Window>
      • View code file.
  9. Handling Events – In the designer window; handle the button’s Click event; then implement the eventhandler method in the code-behind file –
    public partial class MainWindow : Window
    {
     ...
     private void button1_Click(object sender, RoutedEventArgs e)
     {
      this.label1.Content = this.textBox1.Text;
      MessageBox.Show("You entered " + this.textBox1.Text);
     }
    }

    And add this to the XAML to link the events
    Click="button1_Click"
  10. View code file.
  11. Building and running the application:
    • When you build the application, Visual Studio performs the following tasks – Compiles XAML into BAML; Generates partial classes for the application, and for each window –
      BuildingApp
    • To run the application (Ctrl+F5 as usual) –
      RunningApp

Lab 2: Styles

Lab 2: Styles

Overview

  1. A style is a collection of property values that can be applied to an element – Similar to the concept of CSS styles in Web applications.
  2. WPF styles allow you to define common characteristic – UI properties, Non-UI properties.
  3. How Styles Work:
    • WPF elements have a Style property:
      • You assign a Style object to this property.
      • The style is automatically inherited by all child elements.
    • The Style object has a Setters property:
      • Contains a collection of Setter objects.
    • Each Setter object specifies:
      • Property: A dependency property (e.g. Control.FontFamily).
      • Value: The value to set it to (e.g. “Verdana”).
Lab
  1. Example: Define a one-off style for a Button element – UsingStyles project and SimpleStyle.xaml –
    <Window x:Class="UsingStyles.SimpleStyle" ...>
     <StackPanel>
      <Button Name="Button1">
       <Button.Style>
        <Style>
         <Setter Property="Control.FontFamily"     Value="Verdana" />
         <Setter Property="Control.FontSize"      Value="20"   />
         <Setter Property="Control.HorizontalAlignment" Value="Center" />
        </Style>
       </Button.Style>
       Hello from button 1!
      </Button>
     </StackPanel>
    </Window>

    SimpleHello
  2. View code file.
  3. Defining a Style as a Resource:
    • To make styles more widely available, it is common to define them as resources. Typically at window or application level.
    • For example: StylesAsResources.xaml
      <Window x:Class="UsingStyles.StylesAsResources" ...>
       <Window.Resources>
        <Style x:Key="LoudButtonStyle">
         <Setter Property="Control.FontFamily" Value="Verdana" />
         <Setter Property="Control.FontSize"  Value="20" />
         <Setter Property="Control.FontWeight" Value="Bold" />
         <Setter Property="Control.HorizontalAlignment" Value="Center" />
        </Style>
        ...
       </Window.Resources>
       <StackPanel>
        <Button Style="{StaticResource LoudButtonStyle}">Button 1</Button>
        ...
       </StackPanel>
    • View code file.
  4. Defining a Complex Setter
    • You can define a Setter whose value is a complex object (rather than a simple string) – Set the Setter.Value property to a child element in XAML (or to an object in code).
    • For example: ComplexSetter.xaml
      <Style x:Key="LoudButtonStyle">
       <Setter Property="Control.Background">
        <Setter.Value>
         <LinearGradientBrush>
          <GradientBrush.GradientStops>
           <GradientStopCollection>
            <GradientStop Color="Yellow" Offset="0.0"/>
            <GradientStop Color="Crimson" Offset="0.8"/>
           </GradientStopCollection>
          </GradientBrush.GradientStops>
         </LinearGradientBrush>
        </Setter.Value>
       </Setter>
       ...
      </Style>

      ComplexSetter
  5. View code file.
  6. Automatically applying Styles by type:
    • The story so far:
      • We’ve given our styles a key name
        <Style x:Key="LoudButtonStyle"> ...
      • … And explicitly applied styles by key name, where we want to –
        <Button Style="{StaticResource LoudButtonStyle}" ...>
      • An alternative technique:
        • Assign styles to a target element type (don’t specify a key name) –
          <Style x:Key="LoudButtonStyle"> ...
        • … The style will be applied to all elements of that type by default –
          <Button ...> Note: Can opt out, via Style="{x:Null}"

Lab 3: Data Binding

Lab 3: Data Binding

Overview

  1. WPF provides very rich support for data binding:
    • You can create 1-way and 2-way data bindings.
    • You can bind almost any property on a source object to any dependency property on a target object.
    • You can bind collections (e.g. a LINQ query) to ListBox etc…
      OverViewDataBinding
  2. Data Binding Modes – WPF supports four data binding modes
    DataBindingModel
Lab
  1. Creating a Data Binding:
    • You will usually create a data binding in XAML – Set the target property to a data binding expression, by using a Binding markup extension. Then specify source element, source property, and mode (e.g. OneWay) –
      targetProp="{Binding ElementName=srcElem, Path=srcProp, Mode=OneWay}"
  2. Example: element binding:
    • Simple example of how to bind to an element property: Bind TextBlock FontSize property to Slider Value property.
    • Example: GettingStartedWithDataBinding project and BindingToElementProperties.xaml
      <StackPanel>
       <Slider Name="FontSizeSlider" Minimum="10" Maximum="50" Value="20".../>
       <TextBlock Name="MyTextBlock" Text="Hello World!"
           FontSize="{Binding ElementName=FontSizeSlider, Path=Value}".../>
      </StackPanel>

      EleBinding
  3. View code file.
  4. Binding Objects to a GUIPrinciples:
    • You often want to bind several properties in a class to controls in the GUI:
      • E.g. bind each property to a text box in a panel.
    • If you want to support two-way binding, implement the class as follows:
      • Implement the INotifyPropertyChanged interface.
      • Define a PropertyChanged event.
      • Define an OnPropertyChanged() method to raise the event.
      • In each property setter, invoke OnPropertyChanged().
  5. Defining a Class to Support 2-Way Binding.
  6. Example: ObjectBinding project
    public class Product : INotifyPropertyChanged
    {
     public event PropertyChangedEventHandler PropertyChanged; 
     protected void OnPropertyChanged(string propertyName)
     {
      if (this.PropertyChanged != null)
      {
       PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
      }
     }
     private int productID;
     public int ProductID
     {
      get
      ...
      set
      ...
     }
     ...
  7. View code file.
  8. Binding an Object:
    • To bind multiple properties to the same object:
      • Set the DataContext property on the UI control.
      • Establishes a “default” data source for the element.
        <Grid Name="OneProductGrid" ...>
         ...
         <TextBlock Text="Product ID:" />
         <TextBox  Text="{Binding Path=ProductID}" />
         ...
        </Grid>

        public partial class ViewProduct : Window
        {
         Product product = new Product();
         public ViewProduct()
         {
          InitializeComponent();
          OneProductGrid.DataContext = product;
         }
        ...
        }
      • View code file.
      • View code file.
    • Binding a Collection of Objects:
      • If you want to bind a collection of objects to a control (e.g. a ListBox); set the ItemsSource property on the UI control
        <ListBox Name="ProductsListBox1" />
        <ListBox Name="ProductsListBox2" DisplayMemberPath="ProductName" />
        <Button Name="GetProductsButton" Content="Get Products" Click="GetProductsButton_Click" />

        private void GetProductsButton_Click(object sender, RoutedEventArgs e
        {
          List<Product> products = "get a collection of products" ;
          this.ProductsListBox1.ItemsSource = products;
          this.ProductsListBox1.ItemsSource = products;
        }

        BindingCollection
    • View code file.
    • View code file.

 

Well done. You have completed the tutorial in the C# course. The next tutorial is

15. Overview of WCF


Back to beginning
Copyright © 2016 TalkIT®






If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Scroll to Top