Wednesday, June 29, 2011

Markup Extensions in XAML

You can specify a value to an attribute using curly braces ‘{}’ is called as Markup Extensions in XAML. The most commonly used markup extensions in WPF are Binding, StaticResource, DynamicResources, RelativeSource, TemplateBinding etc. These all markup extensions are default provided by WPF. If you want you can create your own Markup Extension you can achieve it by deriving MarkupExtension class. Nested Markup Extensions also possible in XAML.

<Style x:Key="MyStyle" TargetType="{x:Type Button}">
    <Setter Property="Background" Value="Red" />

      <Button Content="Click Me!" Style="{StaticResource MyStyle}" />

In above example Style attribute of Button uses StaticResource Markup Extension.

Tuesday, June 28, 2011

XAML Namespaces and Root Elements

In XAML file you can specify only one Root element. Root element for XAML file can be Window, Page, ResourceDictionary, Application etc. You can specify various elements inside root element.

<Window x:Class="WpfApplication1.DynamicLookup"
        Title="DynamicLookup" Height="300" Width="300">
        <local:Employee x:Key="MyEmployee" />
        <Button Background="LightBlue" Content="Click Me!"
                Height="40" Width="150">

In above example Window element is root element. It contains Grid element as child element. You can see xmlns attribute specified with Window element is called as XAML Namespace. You can also specify your own namespace. In above example you can see xmlns:local attribute specified with Window element which represent WpfApplication1 namespace in your xaml file. Using ‘local:’ prefix you can access classes and properties available in WpfApplication1 namespace. In above example i created one instance of an Employee class available in WpfApplication1 namespace.

When you create new WPF application your XAML file loads with two namespaces. One is default namespace use only ‘xmlns’ attribute and another one is ‘xmlns:x’. The ‘x’ prefix is mapped with The x: prefix provides several programming constructs which can be used in XAML file. Here are few examples of x: prefix which are mostly used in XAML file.

x:Key – Used to set unique key for resource in resource dictionary.

  <Style x:Key="MyStyle" TargetType="Button"> 
     <Setter Property="Background" Value="Red" />

x:Name – You can specify name of an element at runtime.  Generally Framework element has Name property but in some cases you might need to use x:Name when framework element level Name property not supported for particular type.

<Button x:Name="MyButton" Content="Click Me!" />

x:Type – This is used to specify attributes which accepts type.

  <Style x:Key="MyStyle" TargetType="{x:Type Button}">
    <Setter Property="Background" Value="Red" />

x:Static – You can refer static members directly in XAML using this prefix.

<TextBlock Text="{x:Static local:Test.MyStatic}" />

Monday, June 27, 2011

Introduction to XAML

In this post I will explain about XAML and its various parts.

What is XAML?

XAML (Extensible Application Markup Language) is new markup language introduced with WPF. It is created based on XML. XAML is not only used by WPF applications but it can be used by Silverlight, WF and other applications which support XAML. XAML is declarative language. You can create and run WPF application without XAML code and use code behind for the same. But you if you use XAML to write UI you need to write very less code compare to code behind. Writing code in XAML is very short and easy to read.     

XAML and Code behind

    <Button Name="TestButton" Content="Click Me!"
     Height="35" Width="150">

You need to write below code in code behind file to achieve equivalent to above XAML code.

Grid grd = new Grid();

Button btn1 = new Button();
btn1.Content = "Click Me!";
btn1.Name = "TestButton";
btn1.Height = 40;
btn1.Width = 150;

Grid.SetColumn(btn1, 0);
Grid.SetRow(btn1, 0);



Type Conversion

XAML implicitly converts from one type to another. When you specify background of button using XAML you simply type sting but WPF internally converts it in System.Windows.Media.Brushes.

<Button Background="LightBlue" />

If you want to achieve the same in code behind you need to write following code.

Button btn1 = new Button();
btn1.Background = System.Windows.Media.Brushes.LightBlue;

Attribute and Property Element Syntax

You can specify value of properties using attribute syntax as well using property element syntax. In some cases you can’t specify value using attribute syntax so you have to use property element syntax in such cases.

Attribute Syntax

<Button Content="Click Me!" Background="LightBlue"
        Height="40" Width="150">

Property Element Syntax

    <Button.Content>Click Me!</Button.Content>
            <GradientStop Color="Blue" Offset="0" />
            <GradientStop Color="Cyan" Offset="1" />

Some properties can’t be set using attribute syntax. In above example we fill background of button using LinearGardientBrush with property element syntax which is not possible to set using attribute syntax.

XAML File compilation process

WPF application contains XAML and XAML.CS files. When you compile your application it will first XAML file into BAML and CS file into g.cs. For e.g. you application contains Window1.xaml and Window1.xaml.cs file then compiler converts it to Window1.baml and Window1.g.cs files. BAML stands for Binary Application Markup Language and g stands for generated. Compiler uses BAML and g.cs files to generate executable.

BAML file is compiled version of XAML so it’s not human readable format but it is more efficient for loading and parsing at runtime. BAML files are optimized for faster loading at runtime. The g.cs file contains code to load BAML from the executable and create UI. These both files are stored in Obj\Debug and Obj/Release folder of application’s local folder respectively. 

Friday, June 24, 2011

WPF Class Hierarchy

In this post I will explain in brief about WPF Class Hierarchy. 

Major UI Elements are contained in PresentationFramewok assembly of Managed WPF layer. You can read more about WPF Architecture here. It is helpful to take a look at WPF class hierarchy to get more clear idea about WPF controls. Below diagram contains core and fundamental classes of WPF.     

Dispatcher Object
WPF uses single threaded model it means entire UI is owned by single thread. So you can’t access UI Elements from another thread. To overcome with this situations WPF introduced dispatcher. Almost all UI Elements are derived from DispatcherObject class. This class contains two methods CheckAccess and VerifyAccess. CheckAccess method returns true if calling thread has access to this object and VerifyAccess throws an exception if calling thread does not have access to that object. So using this simple functionality all WPF objects are being able to determine that they only used by UI Thread.

Dependency Object
Dependency Object is the base class that supports Dependency Property and Attached Property. The Dependency Properties are used in Data Binding. You can create your own Dependency Property by deriving Dependency Object to you own class. Dependency Object has two Major methods GetValue and SetValue. GetValue method used to get value from Dependency Property and SetValue method used to set value to Dependency Property. I will explain more about data binding in my future posts.

Each and every element that has visual representation and appears in WPF Window is derived from Visual class. Visual class provides some basic Drawing functionality to encapsulate drawing instructions also some drawing related information like clipping, opacity etc. It also has some basic methods to add and remove visuals. Visual class also provides link between managed libraries and milcore.dll that renders display. You can read more about milcore.dll here.

UI Element
UI Element added support for Layout, Focus, Input, Event, command bindings etc. These are core and essential features of WPF. At UI element level basic layout is introduced – Measure and Arrange passes. Measure allows determining that how much size it would take and Arrange allows a parent to determine final size of each child. UI Element also introduce notation of command binding.

Framework Element
Framework element extends layout features of UI Element and adds support for features like data binding, animation and styles. It also supports key properties like HorizontalAlignment, VerticalAlignment, and Margin etc. 

Control is base class for almost all controls available in WPF such as Button, StatusBar, Combobox, Label etc. At this level many control level properties introduced like background, foreground and Font related properties like FontSize, FontStyle, FontWeight etc.

You can read about WPF Architecture  here.

Thursday, June 23, 2011

WPF Architecture

The Major components of WPF Architecture are Presentation Framework, Presentation Core and Media Integration Layer. The architecture divides in three major groups Managed Layer, Media Integration Layer (Unmanaged code) and Core Operating System.

Managed layer contains WindowsBase, Presentation Framework and Presentation Core assembly. Media Integration Layer contains Milcore(Media Integration Library Core)  and WindowsCodecs modules and both are unmanaged code. Media Integration Layer interacts with Direct3D and Direct3D interacts with Device Driver.

Presentation Framework – Holds top level WPF types includes Window, Controls, Styles, and Layout Panels etc. The code and controls written in WPF Application is mostly interacting with this layer.

Presentation Core – Holds base types such as UI Element and Visual. Almost all the controls you are directly interacting with are derived from these types. Presentation Framework uses most of the types defined in this layer.

MilCore – Media Integration Library is core rendering system. MIL is unmanaged code. This layer converts WPF elements into the format that Direct3D expects. Windows7 and Windows Vista uses this assembly to render its Desktop.

WindowsCodecs– provides supports for imaging like image processing, image displaying and scaling etc.

Direct3D – This layer is used to render graphics created using WPF Applications. 

Wednesday, June 22, 2011

Introduction to WPF

What is WPF?

Windows Presentation Foundation (WPF) is next generation presentation system to create applications with a rich UI. WPF application uses hardware acceleration of graphic cards so it will improve your application performance. WPF introduced new markup language called XAML which allows you to keep separate UI and code behind. So designer and developers both can work together. WPF has rich control set and all controls are highly customizable using control templates and different styles. WPF supports Vector based graphic system. So you can easily scale your UI elements. WPF also supports 2D and 3D Graphics, Flow Documents and multimedia. You can create Standalone Application and Browser Hosted Applications (XBAP) using WPF.

Below diagram summaries all the major features of WPF. 

Thursday, June 16, 2011

Difference between ‘dynamic’ and ‘var’ keyword

dynamic vs. var keyword

The major difference between ‘var’ and ‘dynamic’ keyword is when using ‘var’ keyword the type is known at compile time while using ‘dynamic’ keyword the type is known at runtime. ‘var’ keyword is strongly implicitly typed variable and compiler knows type of variable from the initialization. You can see the difference between both in below images.

On mouse hover over the ‘dynamic’ keyword

On mouse hover over the ‘var’ keyword

If you don’t initialize ‘dynamic’ type at the time of declaration then it is ok for compiler. But if you don’t initialize ‘var’ type at time of declaration you will get compile time error.

dynamic d; //ok
var t = "Test"; //ok
var k; //compile time error

The ‘dynamic’ type is also helpful when you are interacting with COM APIs.

Wednesday, June 15, 2011

Dynamic keyword – What’s new in C# 4.0

Dynamic keyword is introduced in C# 4.0. Dynamic operations are checked at runtime not at compile time. This is also known as Duck Typing (A style of dynamic typing). No IntelliSense available with dynamic type (when you press ‘.’) because dynamic type will be resolved at runtime. You can data bind dynamic object. You can go through my separate post for more information about binding dynamic object here.

The Dynamic Language Runtime (DLR) provides infrastructure to support dynamic type in C#. It also provides implementation of dynamic programming language such as IronPython and IronRuby so from C# application you can talk with dynamically typed programming languages like Python and Ruby.   

You can use dynamic as type in Property, Method parameters, Indexer, return value etc. Please see below examples.

dynamic d = 25;
Console.WriteLine(d.GetType().ToString()); //GetType checked at runtime.


public class Employee
    public string EmployeeName { get; set; }
    public int EmployeeAge { get; set; }
    public Employee(string name, int age)
        EmployeeName = name;
        EmployeeAge = age;
    public string GetEmployeeDetails()
        return EmployeeName;

dynamic d = new Employee("Mitesh", 29);
Console.WriteLine(d.GetEmployeeDetails()); //GetEmployeeDetails() method checked at runtime.
Console.WriteLine(d.GetDepartment()); //gives runtime error bcoz no method available named GetDepartment in Employee class



You can’t use Lambda expression / LINQ queries as an argument to dynamic object.

dynamic colleciton = new List<string>();
var result = colleciton.Select(str => str + ","); //compile time error

var strCollection = from string s in colleciton
                    select s;  //compile time error

Monday, June 13, 2011

Named and Optional Arguments – What’s new in C# 4.0

Microsoft introduced new feature called Named and optional arguments in C# 4.0. This feature is already available in Visual Basic. This feature allows user to enter optional and named arguments with method parameters. These are two different features but mostly used together.

Optional parameter is declared by simply declaring default value for it. In below example parameter “s” and “b” are optional parameters. If you don’t specify any arguments for optional parameters it will use default values. You can specify optional parameters for Method, Constructor and indexer.  

private void Test(int a, string s= "Test", bool b= false)

Test(45, "Mitesh", true); // Valid
Test(33); // Valid
Test(44, false); // Invalid

C# doesn’t allow you to omit arguments between commas instead you can specify name with argument. You don’t need to remember order of parameters you simply specify argument with name of parameter.  

Test(44 ,, false); // Invalid, Comma separated gapes are not allowed


Test(44 ,b:false); // Valid
Test(36, b:true, s:"MyName"); // Valid
Test(b:true, 56); // Invalid, Named arguments must be specified after all fixed arguments

  • Optional parameters must be added only after all required parameters.
  • Named arguments must be specified after all fixed arguments.

    Note: Ref keyword is also optional when you using COM and passing object as reference.

    Friday, June 10, 2011

    yield statement

    Yield statement can be used in Iterator block and return value to Enumerator Object. This statement was first introduced in dotnet framework 2.0. You can use Yield return or yield break in your Iterator block. Yield break statement you can use to stop execution of iterator block with no return value. This can be used with LINQ query (see below example).

    Here are some restrictions for using yield statement.

    • Yield statement can be added only inside Iterator Block.
    • You cannot use Yield statement inside Anonymous Method or Lambda Expression.
    • You can’t use “return” statement in iterator block instead you must use “yield break” statement.
    • You can’t use Yield statement in Try block with catch but you can use it in Try block with finally.
    • You can’t write Yield statement in finally block of your try…catch statement.
    • You can’t pass parameters as ref or out to Iterator method.

    public partial class YieldStatement : Window
        public YieldStatement()

            foreach (int k in Square(10))
                Console.Write(k.ToString() + " ");
        public IEnumerable<int> Square(int limit)
            for (int i = 1; i <= limit; i++)
                yield return i * i;


    1 4 9 16 25 36 49 64 81 100

    public partial class YieldStatement : Window
        public YieldStatement()

            var result = from string s in GetValues(true)
                         where s.Length > 3
                         select s;
            foreach (string s in result)
        public IEnumerable<string> GetValues(bool stop)
            yield return "One";
            yield return "Two";
            yield return "Three";
            if (stop)
                yield break;
            yield return "Four";
            yield return "Five";


    In first example, user invokes Square method; it multiplies number and return using yield return keyword. So user will get multiplied number start from 1 to entered limit.

    In second example, user will receive string values having more than three characters. I passed true as parameter so I got only “Three” as output. This is because of “yield break” statement. If I pass false as parameter then I will get “Three”, “Four” and “Five” as output.