Showing posts with label WPF. Show all posts
Showing posts with label WPF. Show all posts

Wednesday, June 25, 2014

WPF Page Hosted Windows Applications and XAML Browser Applications (XBAPs)

WPF Page Hosted Windows Applications and XAML Browser Applications (XBAPs)

In WPF, you can also make page based applications. These page based applications are of two types:

1. Pages Hosted in Windows Application
2. Stand-alone XAML Browser Application(XBAPs)

Lets try to understand these WPF Page based applications:

1. Pages Hosted in Windows Application

In this approach, you create your windows application and host some of the pages in that Windows application using NavigationWindow or Frame. This approach is generally used in WPF applications to integrate some kind of wizard in your application, to show some help contents and documentation.

Hosting Pages in Navigation Window

System.Windows.Controls.Page class is used as top level container instead of Windows. 

<Page...>
...
...
</Page>

But actually, there is one more top level container known as NavigationWindow (derives from Windows class) in which Page container is hosted. The NavigationWindow looks like an ordinary window aside from the backward and forward buttons that appear in the bar at the top. Page class is derived directly from FrameworkElement class. You can add a page to any WPF project. Just choose Project --> Add Page in visual studio.

Hosting Pages in other Window

You have to use Frame class to host your page inside other windows. You can use several frames in your window. You have to use the Source property of the Frame class to point to the page which you want to host.

<Window...>
  ....
  ....
  <Frame Source="Page2.xaml"></Frame>
  ....
  ....
</Window>

Hosting Pages in other Pages

You can also host your page into another page. Again you have to use Frames for this task. Just keep a frame container in other page where you want to host your page.

Ways to move from one page to another:

1. Forward and Back Button:

Set Page.ShowNavigationUI property set to true to show the forward and back button. By default, the property is set to true. There is also one more property called NavigationUIVisibility property which you can use to hide/show the Navigation buttons. By default its value is Automatic. But you can set it to Hidden or Visible as per your need.

2. Hyperlinks

Hyperlinks include NaviageUri property using which you can jump from one page to another.

Example: 

Navigating to other page: 

<Textblock>Click <Hyperlink NavigateUri="Page2.xaml">here</Hyperlink></TextBlock>

Fragment Navigation: Navigating to other page and at specific control on that: 

<Textblock>Click <Hyperlink NavigateUri="Page2.xaml#myTextBox">here</Hyperlink></TextBlock>

You will land on Page2.xaml and scroll up to the myTextBox control. But myTextBox control will not have any focus.

Navigating to websites:

<Textblock>Click <Hyperlink NavigateUri="http://theprofessionalspoint.blogspot.com">here</Hyperlink></TextBlock>

2. Stand-alone XAML Browser Application(XBAPs)

Page Based Applications run directly on IE or Firefox and you don't have to install this application. Just point your browser to correct location. This model is called XBAP. Client system must have .NET framework installed to run the XBAP application. The XBAP applications have limited permissions like XBAP applications cannot write files, cannot interact with system resources and registry, cannot connect to databases etc. But you can give permissions to XBAP applications when required.

To create XBAP application, you have to choose WPF Browser Application template in Visual Studio. After that if you see csproj file, you will find these four elements which point that it is a XBAP application:

<HostInBrowser>True</HostInBrowser>
<Install>False</Install>
<ApplicationExtension>.xbap</ApplicationExtension>
<TargetZone>Internet</TargetZone>

Related Article: To know the difference between Windows and Page Controls, visit my previous post.

Saturday, June 7, 2014

Localization and Satellite Assemblies in WPF: How to support Localization in your WPF application?

Localization and Satellite Assemblies in WPF: How to support Localization in your WPF application?

In WPF applications, the unit of localization is the XAML file (technically, the compiled BAML resource that is embedded in your application). If you want to support three languages, you need to include three BAML resources. Satellite assemblies play an important role in localization of WPF applications. When you create a localized WPF application, you place each localized BAML resource in a separate satellite assembly.

To add localization support to your WPF application, just go to your .csproj file and add <UICulture>en-US</UICulture> under <PropertyGroup> element. Now Build your project and you will get a folder named en-US created where your exe is placed. 

If you go inside this folder, you will get an assembly with the same name as that of your exe but with different extensions. For example, if your application exe name is MySampleApplication.exe, its name would be MySampleApplication.resources.dll. This is called satellite assembly.

Now if you closely examine the size of your exe, it would be reduced because the BAML file is not embedded to it, but it is now contained in the satellite assembly which you just created.

When you run this application, the CLR automatically looks for satellite assemblies in the correct directory based on the computer's regional settings and loads the correct loacalized resource.

For example, if you are running in the fr-FR culture, the CLR will look for an fr-FR subdirectory and use the satellite assemblies it finds there.

Note: Extension for satellite assembly is .resources.dll.

How to localize your WPF application?

Step 1 (msbuild and Uid)

Add UID attribute to all the elements in your WPF application, you want to localize. You can use MSBUILD for adding the UID attribute to all elements used in your all the XAML files througout the application.

msbuild /t:updateuid MySampleApplication.csproj

Step 2 (LocBaml)

To extract the localizable content of all your elements, you need to use the LocBaml command-line tool. To extract the localizable details, you point LocBaml to your satellite assembly and use the /parse paramenter as shown here:

lcobaml /parse en-US\MySampleApplication.resources.dll

A .csv file will be generated named MySampleApplication.resources.csv

Step 3 (Build Satellite Assembly for other cultures e.g. fr-FR)

Again use locbaml tool with /generate parameter to create a satellite assembly with culture fr-FR.

locbaml /generate en-US\MySampleApplication.resources.dll
               /trans:MySampleApplication.resources.French.csv
       /cul:fr-FR /out:fr-FR

Friday, June 6, 2014

WPF Elements and Controls: Basic Concepts and Questions

WPF Elements and Controls: Basic Concepts and Questions

In this article, I have covered very basic concepts of WPF Elements and Controls in the form of questions and answers like the difference between elements, controls, content controls, headered content controls and layout containers, difference between tooltip and popup, difference between radiobutton and checkboxes, lexicon file etc. Last question illustrates the difference between resource files and content files in WPF (this question is out of the blog post title as these files are not WPF elements).

1. What is the difference between WPF Elements and WPF Controls?

There is a difference between WPF Elements and WPF Controls. All the WPF Controls are WPF Elements but vice-versa is not true. Any WPF element which can receive focus and accepts inputs from keyboard or mouse is called WPF Control.

For example: Textbox, Button are WPF Controls.

Exceptions: Tooltip and Label are also considered as WPF Controls because Tooltip appears and disappears depending on user's mouse movement. Similarly, Labels support mnemonics (shortcut keys), that's why Labels are also considered as WPF Controls.

Note: All the WPF Controls are derived from System.Windows.Control class.

2. What is the difference between WPF Controls and WPF Content Controls?

A WPF Content Control is the Control that can hold and display a piece of content.

For example: Button, RadioButton, CheckBox, Label, Tooltip, ScrollViewer, UserControl, Window etc.

Note: All the WPF Content Controls are derived from System.Windows.ContentControl Class.

3. What is the different between WPF Content Controls and Headered Content Controls?

Headered Content Controls are the Content Controls which have both content region and header region which can be used to display some sore of title.

For example: GroupBox, TabItem and Expander

Note: All the WPF Headered Content Controls are derived from HeaderedContentControl class.

4. What is the difference between WPF Content Controls and WPF Layout Containers?

WPF Content Controls can contain only a single nested element while layout containers can contain as many nested elements. You can also take a lot of elements in Content Controls but the condition is that all the elements should be wrapped in a single parent layout container like stackpanel or grid.

5. What is the difference between Label and Textblock in WPF?

Label and Textblock are used to display the content on the screen. The basic difference is that Label support mnemonics (shortcut keys) while Textblock does not. If you do not want shortcut features, you can simply use Textblock as it is lightweight and also supports text wrapping which label does not.

6. What is the different between RadioButton and CheckBox in WPF?

You can do grouping in RadioButton but not in CheckBoxes.

For example: If you place 3 radio buttons in a stack panel, all the radio buttons in that stack panel are grouped i,e you can select any one of them but that feature is not there in CheckBoxes.

Note: Button, RadioButton and CheckBox are derived from ButtonBase class. Further, RadioButton and CheckBox are derived from ToggleButton class.

7. What is the different between Tooltip and Popup in WPF?

There are many differences between WPF Tooltip and Popup:

A) You cannot put user interactive controls in Tooltip as it cannot accept focus but same is possible in Popup.

B) Tooltip is opened and closed automatically when mouse is hovered but Popup does not.

8. How will you get the list of all the fonts installed on your system in WPF?

I will use static SystemFontFamilies collection defined in the System.Windows.Media.Fonts class.

foreach (FontFamily fontFamily in Fonts.SystemFontFamilies)
{
  lstFonts.Items.Add(fontFamily.Source);
}

9. What is the lexicon file in WPF? What is its use?

Lexicon file with exetension .lex is used to create customize the dictionary which is used for spell checking feature in WPF. In your WPF application, when you enable spell checking feature, WPF uses its default dictionary to recognize the words. If you want to add some extra words to that dictionary, you will have to create a lexicon file and add your words there. WPF supports dictionaries in English, German, Spanish and French.

10. What is the difference between Resource Files and Content Files in WPF?

1. Resource files are embedded into the assembly (exe or dll) while content files do not embed with assembly.

2. Content files are used instead of resource files in following scenarios:

A) You want to change the resource file without recompiling the application.
B) The resource file is very large.
C) The resource file is optional and may not be deployed with the assembly.
B) The resource file is a sound file.

How to make a resource file? Just add a file (say any image file) and set its Build Action to Resource (which is by default) in Properties Window.

How to make a content file? Just add a file (say any image file) and set its Build Action to Content in Properties Window. Set Copy to Output Directory to Copy Always.

For example: Suppose you have added a .jpg file of 30KB to your application as a resource. After you Build your application, you will notice an increase of approximately 30KB size in your exe. But if you use same file as content, there will be no increase in the size of exe, but you will notice that same file will be copied in the exe directory.

Related articles: I have written two posts on commonly asked WPF questions and answers. If you are looking for something like that, you can visit Part 1 and Part 2.

Tuesday, June 3, 2014

WPF XAML: Property-Attribute and Property-Element Syntax for Simple and Complex Properties

WPF XAML: Property-Attribute and Property-Element Syntax for Simple and Complex Properties

Property-Attribute and Property-Element are the two approaches in WPF XAML to set the properties of the elements. I will take a very simple example to clear the concepts of both of the Property-Attribute and Property-Element approaches. Lets try to set the background property of the grid. I want to fill the background of the grid with some gradient color. Lets see how can we do this using XAML in WPF?

Suppose I have to set the background of the grid to Green. I will set it like this:

<Grid Name="MyGrid" Background="Green">
....
....
</Grid>

In the above case, I have used Property-Attribute syntax for setting the Background property. WPF has used default brush and painted the area with solid color. But what if you want to use some complex brush and want to paint the background with gradients instead of simple solid color? 

In this scenario, you will have to use Property-Element syntax defined in WPF XAML. Property-Element syntax is represented as ElementName.PropertyName. For example, you have to use Background property in this case as Grid.Background.

So, to introduce gradients in my example, I will have to use LinearGradientBrush instead of the default brush used by WPF for solid fill.

<Grid Name="MyGrid">
  <Grid.Background>
    <LinearGradientBrush>
     <LinearGradientBrush.GradientStops>
       <GradientStop Offset="0.00" Color="Red" />
<GradientStop Offset="0.50" Color="Indigo" />
<GradientStop Offset="1.00" Color="Violet" />
     </LinearGradientBrush.GradientStops>
</LinearGradientBrush>
  </Grid.Background>
</Grid>

In the above example, I have chosen different gradient colors (Red, Indigo and Violet) to paint the background of the Grid.

With this, I think I have cleared the concept of Property-Attribute and Property-Element syntax used in WPF XAML.

Monday, June 2, 2014

WPF XAML Namespaces, Prefixes and Conventions

WPF XAML Namespaces, Prefixes and Conventions

In WPF, XAML contains namespaces for defining controls for your XAML document. You can also map other .NET namespaces to XML namespaces and use them in XAML document. There are some conventions for using prefixes with these namespaces in XAML. Lets go point to point to explore everything about XAML namespaces, prefixes used with namespaces and conventions for using prefixes in XAML.

<Window x:Class="SampleApplication.MainWindow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="MainWindow" Height="350" Width="525">
  <Grid>       
  </Grid>
</Window>

1. xmlns attribute is a specialized attribute in the world of XML that is reserved for declaring namespaces.

2. The above default XAML code contains two XAML namespaces. 

http://schemas.microsoft.com/winfx/2006/xaml/presentation contains all the WPF classes, including the controls you use to build your user interface. This namespace is declared without any prefix, so this is the default namespace for the entire XAML document. Every element in XAML document, is automatically placed in this namespace unless you specify otherwise.

http://schemas.microsoft.com/winfx/2006/xaml includes various XAML utility features. This namespace is mapped to the prefix "x". That means you can apply it by placing prefix "x" before the element name.

3. The above namespaces are not URI unlike in XML.

4. You can also include .NET namespaces like System in XAML for string manipulation. Syntax for including external namespaces in XAML is:

xmlns:Prefix="clr-namespace:Namespace;assembly=AssemblyName"

For example, you can include System namespace in XAML like this:

xmlns:sys="clr-namespace:System;assembly=mscorlib"

Now you can use sys in your XAML document like this:

<sys:DateTime>10/30/2014 5:30 PM<sys:DateTime>

Similarly you can include you custom namespace that you have created in your project like this:

xmlns:local="clr-namespace:MyWPFApplication"

5. Prefix Conventions: In the above examples, I have take x, sys and local prefixes for declaring namespaces. You can take any prefix of your choice, but you should not do it because WPF says to follow this convention for prefixes while declaring XAML namespaces.

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.