Saturday, May 31, 2014

WPF XAML, Loose XAML and BAML Files: Approaches to create WPF applications with XAML

WPF XAML, Loose XAML and BAML Files: Approaches to create WPF applications with XAML

There are four approaches to create WPF application with XAML. You can use XAML directly to in WPF application or can convert XAML into the BAML for improving its performance or you can use loose XAML or do not use XAML at all. Lets try to understand these approaches of creating WPF applications with XAML.

Code and compiled markup(BAML): This is the preferred approach for WPF applications. This approach is used by Visual Studio. You can create XAML template for each window, and this XAML is compiled into BAML and embedded in a final assembly. At runtime, the compiled BAML is extracted and is used to generate the user interface.

Code and uncompiled markup(XAML): You can use this approach when you are creating highly dynamic user interface. In this approach, you load the user interface from a XAML file at runtime using the XamlReader class from the System.Windows.Markup namespace.

Code only: This is the traditional approach used in Visual Studio for Windows Forms application. It generates the user interface through the code statements.

XAML only (Loose XAML): Loose XAML is the file which only contains XAML code without any .NET namespaces, classes, properties, event handlers etc. Loose XAML can be used to stand alone user interface which includes WPF declarative features like animations, triggers, data binding, and links (which can point to other loose XAML files). You can compare loose XAML files with static HTML files. You can open loose XAML files in the Internet Explorer. 

Following points should be considered while creating a loose XAML file:

A) Remove the Class attribute on the root element.
B) Remove any attribute that attach event handlers.
C) Change the name of the opening and closing tag from Window to Page. Internet Explorer can show only hosted pages, not stand-alone windows. 

WPF Layout Controls/Containers, Layout Process, Properties and Tips

WPF Layout Controls/Containers, Layout Process, Properties and Tips

All the WPF Layout containers are panels that derive from the abstract System.Windows.Controls.Panel class. Mainly, there are five layout containers in WPF:

1. StackPanel
2. WrapPanel
3. DockPanel
4. Grid
5. Canvas

I am not going to explain working of all these panels as it is already very well explained here. I will add some extra details about these layout controls in WPF. I will go through WPF Layout Process Stages (Measure Stage and Arrange Stage), how can we create our custom layout containers using MeasureOverride() and ArrangeOverride() methods, different WPF layout properties and some tip and noteworthy points about WPF layout containers.

WPF Layout Process

WPF Layout takes place in two stages:

A) Measure Stage: The container loops through its child elements and asks them to provide their preferred size.
B) Arrange Stage: The container places the child elements in the appropriate position.

Creating WPF Custom Layout Containers

The Panel class also has a bit of internal plumbing you can use if you want to create your own layout containers. Most notably, you can override the MeasureOverride() and ArrangeOverride() methods inherited from FrameworkElement to change the way the panels handle measure stage and arrange stage when organizing its child elements.

WPF Layout Properties

1. Layout Properties of Layout Containers are HorizontalAlignment, VerticalAlignment, Margin, Width, Height, MinWidth, MinHeight, MaxWidth and MaxHeight

2. Default HorizontalAlignment for a Button is Stretch and for a Label is Left.

3. You can set margin for each side of a control in the order left, top, right and bottom. For example:

<Button Margin="1,2,3,4">OK</Button>

In this case, Left Margin = 1, Top Margin = 2, Right Margin = 3 and Bottom Margin = 4.

4. DesiredSize Property: You can find out the size that button wants by examining  the DesiredSize property, which returns the minimum width or the content width, whichever is greater.

5. ActualWidth and ActualHeight Properties: You can find out the actual size used to render an element by reading the ActualHeight and ActualWidth properties. But those values may change when window is resized or the content inside it changes.

6. SizeToContent Property: You can create automatically sized window in WPF if you are creating a simple window with dynamic content. To enable automatic window sizing, remove the Height and Width properties of Window and set the Window.SizeToContent property to WidhtAndHeight. The window will make itselft just large enough to accommodate all its contents. You can also allow a window to resize itself in just one dimension by using the SizeToContent value of Width or Height.

7. Border CornerRadius Property: CornerRadius property allows you to gracefully round the corners of your border. The greater the corner radius, the more dramatic the rounding effect is.

8. WPF Elements should not be explicitly sized.

9. There are three values for visiblity enumeration for elements:

A) Visible: Element is visible
B) Hidden: Element is invisible but the space occupied by it is still reserved.
C) Collapsed: Element is invisible and it also does not take up any space.

WPF Layout Containers - Tips and Noteworthy Points

1. Default orientation of StackPanel is Vertical while default orientation of WrapPanel is Horizontal.

2. DockPanel LastChildFill Property: LastChildFill when set to true, tells the DockPanel to give the remaining space to the last element.

3. DockPanel, Grid and Canvas uses Attached Properties. DockPanel has one attached property: DockPanel.Dock. Grid has two attached properties: Grid.Row and Grid.Column. Canvas has four attached properties: Canvas.Top, Canvas.Left, Canvas.Right and Canvas.Bottom.

4. Grid ShowGridLines Property: ShowGridLines property when set to true, shows all the border of cell and rows.

5. If you don't specify Grid.Row property to the child elements, those child elements are placed on row number 0. Same is the case with Grid.Column.

6. The Grid supports three sizing categories:

A) Absolute Sizes: <ColumnDefination Width="100"></ColumnDefination>
B) Automatic Sizes: <ColumnDefination Width="Auto"></ColumnDefination>
C) Proportional Sizes: <ColumnDefination Width="*"></ColumnDefination>

You can also add weight to proportional sizes: 

<ColumnDefination Width="*"></ColumnDefination>
<ColumnDefination Width="2*"></ColumnDefination>

It means, the second column is twice as bigger as the first one.

7. You can also span rows and columns in a grid.

<Button Grid.Row="0" Grid.Column="0" Grid.RowSpan="2">RowSpannedButton</Button> 

<Button Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2">RowSpannedButton</Button>

8. You can add GridSplitter to a Grid to give the user ability to resize rows and columns.

9. You can also create uniform grids in WPF. Uniform Grids don't require any row and column definition. Example:

<UniformGrid Rows="2" Columns="2">
<Button>Top Left</Button>
<Button>Top Right</Button>
<Button>Bottom Left</Button>
<Button>Bottom Right</Button>
</UniformGrid>

10. All the layout containers can be nested.

11. Canvas is the most lightweight layout container. 

12. Canvas allows you to place elements by using exact coordinates which is a poor choice of designing rich data-driven form.

13. Canvas.ClipToBounds property is used to clip the contents which fall outside the canvas.

14. Canvas.ZIndex property is used when there are overlapping elements in Canvas. The child element having greater ZIndex value will be shown above other child elements.

15. InkCanvas is used to allow stylus input. InkCanvas lets the user annotate contents with strokes.

Friday, May 30, 2014

WPF XAML and BAML: XAML Introduction, Advantages and Compilation

WPF XAML and BAML: XAML Introduction, Advantages and Compilation

This article on WPF XAML covers basic concepts of XAML, Advantages of using XAML into WPF, how XAML elements are related with .NET classes and how XAML in actually compiled in WPF applications. We will get an idea on how WPF XAML code is converted into the BAML and again how BAML code is converted into the XAML and the role of InitializeComponent() method in the process.

XAML stands for Extensible Application Markup Language and is mainly used to create WPF user interface. XAML is also used in Silverlight and WF (Windows Workflow Foundation). You can create XAML using Visual Studio as well as Expression Blend. Basically Visual Studio is for developers and Expression Blend is for designers.

Advantage of XAML in WPF applications

In WPF, due to the introduction of XAML, graphical designer can separately work on user interface and developers can concentrate on the main logic. But it was not possible in Windows Form because any visual element such as label, textbox, button you create in Windows Forms are defined in C# classes. So, the designer could not do anything in that. All the user interface thing had to be taken care by developer itself. Designers could make separate mock-ups for screens in Photoshop etc. which developers had to convert in the C# code which was very much painful. But WPF XAML changed the world. Now designers can directly make screens for developers in XAML and developers just have to bind the elements in the screen with the properties they have made in their C# code.

Relation between XAML Elements and .NET Classes

Every element in XAML document maps to an instance of .NET class. The name of the element matches to the name of the .NET class. For example, the element Button in XAML instructs WPF to create an object of Button class in .NET. XAML element attributes are used to set the properties of .NET classes. 

Note: XAML is case-sensitive language. 

For example: You cannot write below XAML code
<Button Content="Hit Me"></Button>
like this
<button Content="Hit Me"></button>

Conversion of XAML into BAML: XAML Compilation

When you compile your WPF application, all your XAML code is converted into the BAML (Binary Application Markup Language) by XAML parser and is embedded as a resource into the final DLL or EXE. BAML is nothing but the binary representation of XAML. BAML is tokenized, which means lengthier bits of XAML are replaced with shorter tokens. Not only BAML is significantly smaller, but it is also optimized in a way that makes it faster to parse at runtime.

Conversion of BAML into XAML: The InitializeComponent() Method

InitializeComponent() method plays a vital role in WPF applications. Therefore, you should never delete InitializeComponent() call in your window's constructor. Similarly, if you add another constructor to your window class, make sure it also calls InitializeComponent().

InitializeComponent() calls LoadComponent() method of the System.Windows.Application class. The LoadComponent() method extracts the BAML(the compiled XAML) from your assembly and uses it to build your WPF user interface.

Tuesday, May 27, 2014

WPF Introduction, Architecture and Core Classes

WPF Introduction, Architecture and Core Classes

WPF is a modern graphical display system for Windows. WPF has innovative features like built-in Hardware Acceleration and Resolution Independence. 

Before WPF, User32 and GDI/GDI+ components were used for creating user interface which had a lot of limitations. Windows Forms and VB6 used these User32 and GDI/GDI+ components for creating user interface.

To overcome limitations of User32 and GDI/GDI+, DirectX was introduced. DirectX is the highly efficient toolkit of game development on Windows and has support for all modern video cards.

WPF uses DirectX instead of GDI/GDI+. User32 is still used but its use by WPF is very limited.

WPF 4.5 is compatible only with Windows Vista, Windows 7 and Windows 8. For Windows XP, you will have to configure Visual Studio to target .NET 4.0 framework rather than .NET 4.5.

WPF Architecture



















WPF Architecture can be divided into three layers:

1. Managed WPF API Layer includes

A) PresentationFramework.dll: Supports WPF types like windows, panels, styles etc.
B) PresentationCore.dll: Supports base types like UIElement and Visuals.
C) WindowsBase.dll: Supports DependencyObject and DispatcherObject.

2. Media Integration Layer includes

A) milcore.dll: This is the core of WPF rendering system and foundation of the Media Integration Layer. Its composition engine translates all WPF visual elements into triangle and textures that Direct3D expects. Although milcore.dll is considered as a part of WPF; it is also an essential system component for Windows Vista and Windows 7. milcore.dll is an unmanaged component. milcore.dll is implemented in unmanaged code because it needs tight integration with Direct3D and because it is extremely performance-sensitive.

B) WindowsCodecs.dll: It provides imaging support for processing, displaying and scaling of bitmaps and JPEGs.

3. DirectX Layer includes

A) Direct3D: Responsible for rendering WPF graphics.
B) User32: It does not play any role in rendering. It is used to determine what program gets what real estate.

Fundamental Namespaces and Core Classes in WPF


System.Threading.DispatcherObject - Supports Single Threaded Affinity (STA).
System.Windows.DependencyObject - Supports dependency properties.
System.Windows.Media.Visual - Supports drawing objects.
System.Windows.UIElement - Supports Layout, Input, Focus and Events (LIFE as acronym).
System.Windows.FrameworkElement - Supports other elements which are left in UIElement.
System.Windows.Shapes.Shape - Supports shapes like rectangle, polygon, ellipse, line, path etc.
System.Windows.Controls.Control - Supports textboxes, buttons, listboxes etc.
System.Windows.Controls.ContentControl - Base class for all the controls that have a single piece of content like label.
System.Windows.Controls.ItemsControl - Base class for all the controls that show a collection of items like ListBox and TreeView.
System.Windows.Controls.Panel - Base class for all the layout containers.

Core Features of WPF:

1. Hardware Acceleration: All WPF drawing is performed by DirectX. DirectX uses GPU (which is a dedicated processor for Video cards) for creating interactive user interface like textures, gradients, animation, 3D drawing, transparency, anti-aliasing etc.

2. Resolution Independence: WPF is flexible enough to scale up or down to suit your monitor and display preferences. WPF uses DIP (Device Independent Unit) which is 1/96 of an inch.

WPF Toolkit: WPF Toolkit includes a set of controls for creating bar, pie, bubble, scatter and line graphs. For more info on WPF Toolkit, you can visit wpf.codeplex.com.

Monday, May 26, 2014

WPF StaticResource and DynamicResource Examples and Explanations

WPF StaticResource and DynamicResource Examples and Explanations

A WPF Resource is an object that can be reused in different places in your WPF application. Brushes and Styles are the best examples of WPF Resources. WPF Resources are not the part of visual tree but can be used in your user interface. Generally WPF objects are defined as resources, which are used by multiple elements of the application.

WPF Resources are of two types:

1. Static Resource
2. Dynamic Resource

1. StaticResource: StaticResources are resolved at compile time. Use StaticResources when it's clear that you don't need your resource re-evaluated when fetching it static resources perform better than dynamic resources.

Syntax for StaticResource usage: 
<object property="{StaticResource key}" .../> 

2. DynamicResource: DynamicResources are resolved at runtime. Use DynamicResources when the value of the resource could change during the lifetime of the application.

Syntax for DynamicResource usage: 
<object property="{DynamicResource key}" .../> 

Examples of StaticResource and DynamicResource

Step 1: Define a Resource

<Window.Resources>
    <SolidColorBrush x:Key="myBrush" Color="Red" />
</Window.Resources>

Step 2: Use the myBrush resource as StaticResource

<Button x:Name="myButton" Content="OK" Click="Button_Click" Background="{StaticResource myBrush}" />

Step 3: Use the myBrush resource as DynamicResource

<Button x:Name="myButton" Content="OK" Click="Button_Click" Background="{DynamicResource myBrush}" />

Code behind file:

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

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        this.Resources["myBrush"] = new SolidColorBrush(Colors.Green);
    }      
}

Another way: Use SetResourceReference

Syntax for SetResourceReference: 

frameworkElement.SetResourceReference(dependencyProperty, resourceKey);

You could also do the above code behind stuff like this:

this.myButton.SetResourceReference(BackgroundProperty, "myBrush");

It will set the button background to Green color instead of Red.

Further readings:

MSDN: Example of StaticResource and complete explanation on usage of StaticResource and DynamicResource

CodeProject: Example of StaticResource and DynamicResource

Stackoverflow: What is the difference between StaticResource and DynamicResource. When to use what? Akshay J has given a very good example of DynamicResource here.

Rhyous: Examples of StaticResource

Professionals Point: Difference between StaticResource and DynamicResource in WPF

Wednesday, May 21, 2014

Usage of ObservableCollection class and INotifyCollectionChanged interface in WPF Data Binding

Usage of ObservableCollection class and INotifyCollectionChanged interface in WPF Data Binding

The ObservableCollection<T> is one of the most important features of WPF data binding. ObservableCollection is a generic dynamic data collection that provides notifications (using an interface "INotifyCollectionChanged") when items get added, removed, or when the whole collection is refreshed.

Namespace for ObservableCollection: System.Collections.ObjectModel

Syntax for ObservableCollection:

[SerializableAttribute]
public class ObservableCollection<T> : Collection<T>, 
INotifyCollectionChanged, INotifyPropertyChanged
ObservableCollection has a lot of properties, methods, events, explicit interface implementations. Get a complete list on MSDN.

Main feature of the ObservableCollection<T> are the events it raises when the items it contains change. When in your WPF application, you make any changes like remove/add/edit item in the ObservableCollection, the ObservableCollection updates the view controls to which it is binded because it internally implements INotifyCollectionChanged and INotifyPropertyChanged interfaces which are responsible for updating the view. INotifyCollectionChanged interface exposes the CollectionChanged event, an event that should be raised whenever the underlying collection changes.

INotifyCollectionChanged Interface: If you are using ObservableCollection, as I already mentioned, you don't need to implement INotifyCollectionChanged interface because it is already implemented in this class. But, if you want to use List instead of ObservableCollection, you will have to surely implement INotifyCollectionChanged if you want your view to get updated when any change is made to your List.

Implementation of INotifyCollectionChanged

public class ViewModelBase : INotifyCollectionChanged
{
  #region INotifyCollectionChanged
  public event NotifyCollectionChangedEventHandler CollectionChanged;
  private void OnNotifyCollectionChanged(NotifyCollectionChangedEventArgs args)
  {
    if (this.CollectionChanged != null)
    {
 this.CollectionChanged(this, args);
    }
  }
  #endregion INotifyCollectionChanged
}

Similarly,  Implementation of INotifyPropertyChanged

public class ViewModelBase : INotifyPropertyChanged
{
  #region INotifyPropertyChanged
  public event PropertyChangedEventHandler PropertyChanged;
  protected void OnPropertyChanged(string propertyName)
  {
    if (PropertyChanged != null)
 PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
  }
  #endregion INotifyPropertyChanged
}

You can inherit ViewModelBase class where you want to implement INotifyCollectionChanged and INotifyPropertyChanged interfaces.

ObservableCollection Example: 

I found a very good and simple example of ObservableCollection in WPF on CSharpCorner. Although, the author is not using MVVM pattern here for the sake of simplicity, you can convert this example to MVVM also.

Tuesday, May 20, 2014

Basics of WPF ICommand Interface in MVVM

Basics of WPF ICommand Interface in MVVM

I am going to cover basics of ICommand interface in WPF in MVVM pattern like syntax of ICommand interface, methods and events of ICommand interface, how to bind ICommand in View(XAML), how to implement ICommand interface in ViewModel etc. 

1. Namespace for ICommand

System.Windows.Input
Assembly: System

System.Windows.Input supports many Classes, Structures, Interfaces, Delegates and Enumerations. Here is the complete list on MSDN.

2. Methods exposed by ICommand

A) CanExecute: Defines the method that determines whether the command can execute in its current state. Typically, a command source calls the CanExecute method when the CanExecuteChanged event is raised.

Syntax: bool CanExecute(Object parameter)

Parameter: System.Object
Return Value: Boolean

B) Execute: Defines the method to be called when the command is invoked.

Syntax: void Execute(Object parameter)

Parameter: System.Object

3. Events exposed by ICommand

A) CanExecuteChanged: Occurs when changes occur that affect whether or not the command should execute.

Syntax: event EventHandler CanExecuteChanged

Implement the command by defining a class that implements ICommand and specifically implement the Execute method.

A complete ICommand Interface looks like:

public interface ICommand
{
  void Execute(object parameter);
  bool CanExecute(object parameter);
  event EventHandler CanExecuteChanged;
}

How to use ICommand in View (XAML)?

I am creating a Save button and binding ICommand to it.

<Button Content="Save" Command="{Binding SaveCommand}" CommandParameter="Hello"/>

CommandParameter: A parameter can be passed through the "CommandParameter" property. The CommandParameter is sent to both CanExecute and Execute events.

Further readings: