Friday, November 4, 2016

Introduction WPF (Windows Presentation Foundation)

Introduction WPF (Windows Presentation Foundation)

WPF combines application UIs, 2D graphics, 3D graphics, documents and multimedia into one single framework. Its vector based rendering engine uses hardware acceleration of modern graphic cards. This makes the UI faster, scalable and resolution independent.

The following illustration gives you an overview of the main new features of WPF:
1.       Declarative UI with XAML.
2.       Multimedia support.
3.       Skinning Support.
4.       XPS Documents.
5.       3D Programming.
6.       Highly Composable.
7.       Animation and Timeliness.
8.       Powerful Data binding.
9.       Resolution independence.
10.   Vector based rendering.
11.   Hardware Accelerated (Direct 3D)

Separation of Appearance and Behavior

WPF separates the appearance of a user interface from its behavior. The appearance is generally specified in the Extensible Application Markup Language (XAML), the behavior is implemented in a managed programming language like C# or Visual Basic. The two parts are tied together by data binding, events and commands. The separation of appearance and behavior brings the following benefits:
  • Appearance and behavior are loosely coupled
  • Designers and developers can work on separate models.
  • Graphical design tools can work on simple XML documents instead of parsing code.

Rich composition

Controls in WPF are extremely composable. You can define almost any type of controls as content of another. Although these flexibility sounds horrible to designers, its a very powerful feature if you use it appropriate. Put an image into a button to create an image button, or put a list of videos into a combo box to choose a video file. 

<Button>
    <StackPanel Orientation="Horizontal">
        <Image Source="speaker.png" Stretch="Uniform"/>
        <TextBlock Text="Play Sound" />
    </StackPanel>
</Button>

Highly customizable


Because of the strict separation of appearance and behavior you can easily change the look of a control. The concept of styles let you skin controls almost like CSS in HTML. Templates let you replace the entire appearance of a control.
The following example shows a default WPF button and a customized button.

Introduction to XAML

XAML stands for Extensible Application Markup Language. It’s a simple language based on XML to create and initialize .NET objects with hierarchical relations. Although it was originally invented for WPF it can be used to create any kind of object trees.
Today XAML is used to create user interfaces in WPF, Silverlight, declare workflows in WF and for electronic paper in the XPS standard.
All classes in WPF have parameter less constructors and make excessive usage of properties. That is done to make it perfectly fit for XML languages like XAML.

Advantages of XAML

All you can do in XAML can also be done in code. XAML is just another way to create and initialize objects. You can use WPF without using XAML. It's up to you if you want to declare it in XAML or write it in code. Declare your UI in XAML has some advantages:
  • XAML code is short and clear to read
  • Separation of designer code and logic
  • Graphical design tools like Expression Blend require XAML as source.
  • The separation of XAML and UI logic allows it to clearly separate the roles of designer and developer.

XAML vs. Code


As an example we build a simple StackPanel with a textblock and a button in XAML and compare it to the same code in C#.
<StackPanel>
    <TextBlock Margin="20">Welcome to the World of XAML</TextBlock>
    <Button Margin="10" HorizontalAlignment="Right">OK</Button>
</StackPanel>

The same expressed in C# will look like this:

// Create the StackPanel
StackPanel stackPanel = new StackPanel();
this.Content = stackPanel;
 
// Create the TextBlock
TextBlock textBlock = new TextBlock();
textBlock.Margin = new Thickness(10);
textBlock.Text = "Welcome to the World of XAML";
stackPanel.Children.Add(textBlock);
 
// Create the Button
Button button = new Button();
button.Margin= new Thickness(20);
button.Content = "OK";
stackPanel.Children.Add(button); 

As you can see is the XAML version much shorter and clearer to read. And that's the power of XAMLs expressiveness.
Properties as Elements

Properties are normally written inline as known from XML <Button Content="OK" />. But what if we want to put a more complex object as content like an image that has properties itself or maybe a whole grid panel? To do that we can use the property element syntax. This allows us to extract the property as an own child element.
<Button>
  <Button.Content>
     <Image Source="Images/OK.png" Width="50" Height="50" />
  </Button.Content>
</Button>

Implicit Type conversion


A very powerful construct of WPF are implicit type converters. They do their work silently in the background. When you declare a BorderBrush, the word "Blue" is only a string. The implicit BrushConverter makes a System.Windows.Media.Brushes.Blue out of it. The same regards to the border thickness that is being converted implicit into a Thickness object. WPF includes a lot of type converters for built-in classes, but you can also write type converters for your own classes.
<Border BorderBrush="Blue" BorderThickness="0,10">
</Border> 

 Markup Extensions


Markup extensions are dynamic placeholders for attribute values in XAML. They resolve the value of a property at runtime. Markup extensions are surrounded by curly braces (Example: Background="{StaticResource NormalBackgroundBrush}").
WPF has some built-in markup extensions, but you can write your own, by deriving from MarkupExtension.
These are the built-in markup extensions:
  • Binding
    To bind the values of two properties together.
  • StaticResource
    One time lookup of a resource entry
  • DynamicResource
    Auto updating lookup of a resource entry
  • TemplateBinding
    To bind a property of a control template to a dependency property of the control
  • x:Static
    Resolve the value of a static property.
  • x:Null
    Return null
The first identifier within a pair of curly braces is the name of the extension. All preceding identifiers are named parameters in the form of Property=Value. The following example shows a label whose Content is bound to the Text of the textbox. When you type a text into the text box, the text property changes and the binding markup extension automatically updates the content of the label.
<TextBox x:Name="textBox"/>
<Label Content="{Binding Text, ElementName=textBox}"/>

Namespaces


At the beginning of every XAML file you need to include two namespaces.
The first is http://schemas.microsoft.com/winfx/2006/xaml/presentation. It is mapped to all wpf controls in System.Windows.Controls.
The second is http://schemas.microsoft.com/winfx/2006/xaml it is mapped to System.Windows.Markup that defines the XAML keywords.
The mapping between an XML namespace and a CLR namespace is done by the XmlnsDefinition attribute at assembly level. You can also directly include a CLR namespace in XAML by using the clr-namespace: prefix.


<Window xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”        xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”>
</Window>

Logical- and Visual Tree


Introduction


Logical Tree

Elements of a WPF user interface are hierarchically related. This relation is called the LogicalTree.
In WPF, you add content to UI elements by setting properties of the objects that back those elements. For example, you add items to a ListBox control by manipulating its Items property. By doing this, you are placing items into the ItemCollection that is the Items property value. Similarly, to add objects to a DockPanel, you manipulate its Children property value. Here, you are adding objects to the UIElementCollection.

The Purpose of the Logical Tree

The logical tree exists so that content models can readily iterate over their possible child objects, and so that content models can be extensible. Also, the logical tree provides a framework for certain notifications, such as when all objects in the logical tree are loaded. Basically, the logical tree is an approximation of a run time object graph at the framework level, which excludes visuals, but is adequate for many querying operations against your own run time application's composition.
In addition, both static and dynamic resource references are resolved by looking upwards through the logical tree for Resources collections on the initial requesting object, and then continuing up the logical tree and checking each FrameworkElement (or FrameworkContentElement) for another Resources value that contains a ResourceDictionary, possibly containing that key. The logical tree is used for resource lookup when both the logical tree and the visual tree are present. For more information on resource dictionaries and lookup, see Resources Overview.

Composition of the Logical Tree

The logical tree is defined at the WPF framework-level, which means that the WPF base element that is most relevant for logical tree operations is either FrameworkElement or FrameworkContentElement. However, as you can see if you actually use the LogicalTreeHelper API, the logical tree sometimes contains nodes that are not either FrameworkElement or FrameworkContentElement. For instance, the logical tree reports the Text value of a TextBlock, which is a string.

Visual Tree


The template of one element consists of multiple visual elements. This tree is called the VisualTree.

WPF differs between those two trees, because for some problems you only need the logical elements and for other problems you want all elements.
 <Window>
    <Grid>
        <Label Content="Label" />
        <Button Content="Button" />
    </Grid>
</Window> 

Why do we need two different kinds of trees?


A WPF control consists of multiple, more primitive controls. A button - for example - consists of a border, a rectangle and a content presenter. These controls are visual children of the button.
When WPF renders the button, the element itself has no appearance, but it iterates through the visual tree and renders the visual children of it. This hierarchical relation can also be used to do hit-testing, layout etc.
But sometimes you are not interested in the borders and rectangles of a controls' template. Particularly because the template can be replaced, and so you should not relate on the visual tree structure! Because of that you want a more robust tree that only contains the "real" controls - and not all the template parts. And that is the eligibility for the logical tree.

The Logical Tree


The logical tree describes the relations between elements of the user interface. The logical tree is responsible for:
1.       Inherit DependencyProperty values
2.       Resolving DynamicResources references
3.       Looking up element names for bindings
4.       Forwaring RoutedEvents

The Visual Tree


The visual tree contains all logical elements including all visual elements of the template of each element.
The visual tree is responsible for:
1.       Rendering visual elements
2.       Propagate element opacity
3.       Propagate Layout- and RenderTransforms
4.       Propagate the IsEnabled property.
5.       Do Hit-Testing
6.       RelativeSource (FindAncestor)

Programmatically Find an Ancestor in the Visual Tree


If you are a child element of a user interface and you want to access data from a parent element, but you don't know how many levels up that elements is, it's the best solution to navigate up the tree until it finds an element of the requested type.
This helper does exactly this. You can use almost the same code to navigate through the logical tree.
public static class VisualTreeHelperExtensions
{
    public static T FindAncestor<T>(DependencyObject dependencyObject)
        where T : class
    {
        DependencyObject target = dependencyObject;
        do
        {
            target = VisualTreeHelper.GetParent(target);
        }
        while (target != null && !(target is T));
        return target as T;
    }
}  

The following example shows how to use the helper. It starts at this and navigates up the visual tree until it finds an element of type Grid. If the helper reaches the root element of the tree, it returns null.
 var grid = VisualTreeHelperExtensions.FindAncestor<Grid>(this);

Dependency Properties

Introduction


When you begin to develop an application with WPF, you will soon stumble across DependencyProperties. They look quite similar to normal .NET properties, but the concept behind is much more complex and powerful.
The main difference is, that the value of a normal .NET property is read directly from a private member in your class, whereas the value of a DependencyProperty is resolved dynamically when calling the GetValue() method that is inherited from DependencyObject.
When you set a value of a dependency property it is not stored in a field of your object, but in a dictionary of keys and values provided by the base class DependencyObject. The key of an entry is the name of the property and the value is the value you want to set.

Advantages of Dependency Properties

The advantages of dependency properties are
1.       Reduced memory footprint
It's a huge dissipation to store a field for each property when you think that over 90% of the properties of a UI control typically stay at its initial values. Dependency properties solve these problems by only store modified properties in the instance. The default values are stored once within the dependency property.
2.       Value inheritance
When you access a dependency property the value is resolved by using a value resolution strategy. If no local value is set, the dependency property navigates up the logical tree until it finds a value. When you set the FontSize on the root element it applies to all textblocks below except you override the value.
3.       Change notification
Dependency properties have a built-in change notification mechanism. By registering a callback in the property metadata you get notified, when the value of the property has been changed. This is also used by the data binding.

Value resolution strategy


Every time you access a dependency property, it internally resolves the value by following the precedence from high to low. It checks if a local value is available, if not if a custom style trigger is active... and continues until it founds a value. At last the default value is always available.

The magic behind it


Each WPF control registers a set of DependencyProperties to the static DependencyProperty class. Each of them consists of a key - that must be unique per type - and a metadata that contain callbacks and a default value.
All types that want to use DependencyProperties must derive from DependencyObject. This base class defines a key, value dictionary that contains local values of dependency properties. The key of an entry is the key defined with the dependency property.
When you access a dependency property over its .NET property wrapper, it internally calls GetValue(DependencyProperty) to access the value. This method resolves the value by using a value resolution strategy that is explained in detail below.
If a local value is available, it reads it directly from the dictionary. If no value is set if goes up the logical tree and searches for an inherited value. If no value is found it takes the default value defined in the property metadata. This sequence is a bit simplified, but it shows the main concept.

How to create a DependencyProperty


To create a DependencyProperty, add a static field of type DepdencyProperty to your type and call DependencyProperty.Register() to create an instance of a dependency property. The name of the DependendyProperty must always end with ...Property. This is a naming convention in WPF.
To make it accessible as a normal .NET property you need to add a property wrapper. This wrapper does nothing else than internally getting and setting the value by using the GetValue() and SetValue() Methods inherited from DependencyObject and passing the DependencyProperty as key.
Important: Do not add any logic to these properties, because they are only called when you set the property from code. If you set the property from XAML the SetValue() method is called directly.
If you are using Visual Studio, you can type propdp and hit 2x tab to create a dependency property.
 
// Dependency Property
public static readonly DependencyProperty CurrentTimeProperty = 
     DependencyProperty.Register( "CurrentTime", typeof(DateTime),
     typeof(MyClockControl), new FrameworkPropertyMetadata(DateTime.Now));
 
// .NET Property wrapper
public DateTime CurrentTime
{
    get { return (DateTime)GetValue(CurrentTimeProperty); }
    set { SetValue(CurrentTimeProperty, value); }
}
Each DependencyProperty provides callbacks for change notification, value coercion and validation. These callbacks are registered on the dependency property.
 
new FrameworkPropertyMetadata( DateTime.Now, 
                       OnCurrentTimePropertyChanged, 
                       OnCoerceCurrentTimeProperty ),
                       OnValidateCurrentTimeProperty );

Value Changed Callback

The change notification callback is a static method, that is called everytime when the value of the TimeProperty changes. The new value is passed in the EventArgs, the object on which the value changed is passed as the source.
private static void OnCurrentTimePropertyChanged(DependencyObject source, 
        DependencyPropertyChangedEventArgs e)
{
    MyClockControl control = source as MyClockControl;
    DateTime time = (DateTime)e.NewValue;
    // Put some update logic here...
}

Coerce Value Callback

The coerce callback allows you to adjust the value if its outside the boundaries without throwing an exception. A good example is a progress bar with a Value set below the Minimum or above the Maximum. In this case we can coerce the value within the allowed boundaries. In the following example we limit the time to be in the past.
private static object OnCoerceTimeProperty( DependencyObject sender, object data )
{
    if ((DateTime)data > DateTime.Now )
    {
        data = DateTime.Now;
    }
    return data;
}

Validation Callback

In the validate callback you check if the set value is valid. If you return false, an ArgumentException will be thrown. In our example demand, that the data is an instance of a DateTime.
 
private static bool OnValidateTimeProperty(object data)
{
    return data is DateTime;
}

Readonly DependencyProperties


Some dependency property of WPF controls are readonly. They are often used to report the state of a control, like the IsMouseOver property. Is does not make sense to provide a setter for this value.
Maybe you ask yourself, why not just use a normal .NET property? One important reason is that you cannot set triggers on normal .NET propeties.
Creating a read only property is similar to creating a regular DependencyProperty. Instead of calling DependencyProperty.Register() you call DependencyProperty.RegisterReadonly(). This returns you a DependencyPropertyKey. This key should be stored in a private or protected static readonly field of your class. The key gives you access to set the value from within your class and use it like a normal dependency property.
Second thing to do is registering a public dependency property that is assigned to DependencyPropertyKey.DependencyProperty. This property is the readonly property that can be accessed from external.
// Register the private key to set the value
private static readonly DependencyPropertyKey IsMouseOverPropertyKey = 
      DependencyProperty.RegisterReadOnly("IsMouseOver", 
      typeof(bool), typeof(MyClass), 
      new FrameworkPropertyMetadata(false));
 
// Register the public property to get the value
public static readonly DependencyProperty IsMouseoverProperty = 
      IsMouseOverPropertyKey.DependencyProperty;    
 
// .NET Property wrapper
public int IsMouseOver
{
   get { return (bool)GetValue(IsMouseoverProperty); }
   private set { SetValue(IsMouseOverPropertyKey, value); }
}

Attached Properties 

Attached properties are a special kind of DependencyProperties. They allow you to attach a value to an object that does not know anything about this value.

A good example for this concept is layout panels. Each layout panel needs different data to align its child elements. The Canvas needs Top and Left, The DockPanel needs Dock, etc. Since you can write your own layout panel, the list is infinite. So you see, it's not possible to have all those properties on all WPF controls.
The solution are attached properties. They are defined by the control that needs the data from another control in a specific context. For example an element that is aligned by a parent layout panel.

To set the value of an attached property, add an attribute in XAML with a prefix of the element that provides the attached property. To set the the Canvas.Top and Canvas.Left property of a button aligned within a Canvas panel, you write it like this:
<Canvas>
    <Button Canvas.Top="20" Canvas.Left="20" Content="Click me!"/>
</Canvas>
 
 
public static readonly DependencyProperty TopProperty =
    DependencyProperty.RegisterAttached("Top", 
    typeof(double), typeof(Canvas),
    new FrameworkPropertyMetadata(0d,
        FrameworkPropertyMetadataOptions.Inherits));
 
public static void SetTop(UIElement element, double value)
{
    element.SetValue(TopProperty, value);
}
 
public static double GetTop(UIElement element)
{
    return (double)element.GetValue(TopProperty);
}

Listen to dependency property changes


If you want to listen to changes of a dependency property, you can subclass the type that defines the property and override the property metadata and pass an PropertyChangedCallback. But an much easier way is to get the DependencyPropertyDescriptor and hookup a callback by calling AddValueChanged().
DependencyPropertyDescriptor textDescr = DependencyPropertyDescriptor.
    FromProperty(TextBox.TextProperty, typeof(TextBox));
 
if (textDescr!= null)
{
    textDescr.AddValueChanged(myTextBox, delegate
    {
        // Add your propery changed logic here...
    });
} 

How to clear a local value


Because null is also a valid local value, there is the constant DependencyProperty.UnsetValue that describes an unset value.
button1.ClearValue( Button.ContentProperty );


For details click here.