what is WPF?

WPF (Windows Presentation foundation) is a graphical subsystem for displaying user interfaces, documents, images, movies etc in windows application.

 What is the need of WPF when we had windows forms?

A - Anywhere execution ( Windows or Web)

B - Bindings ( less coding)

C - Common look and feel ( resource and styles)

D - Declarative programming (XAML)

E - Expression blend animation ( Animation ease)

F - Fast execution ( Hardware acceleration)

G - Graphic hardware independent ( resolution independent)

I would strongly suggest you to see the below video which explains all the above A to G points practically.

What is XAML in WPF and why do we need it?

XAML is a XML file which represents your WPF UI. The whole point of creating the UI representation in XML was write once and run it anywhere. So the same XAML UI can be rendered as windows application with WPF and the same UI can be displayed on the browser using WPF browser or Silverlight application.

What is xmlns in XAML file?

“xmlns” stands for XML namespaces. It helps us to avoid name conflicts and confusion in XML documents. For example consider the below two XML which have table elements, one table is a HTML table and the other represents a restaurant table. Now if both these elements come in a single XML document there would name conflicts and confusion.

<table> <tr><td>Row1</td></tr> <tr><td>Row2</td></tr> </table> =============================== <table> <cloth>red</cloth> <serve>Tea</serve> </table>

So to avoid the same we can use XML namespaces. You can see in the below XML we have qualified the HTML table with “” and the restaurant table element qualified with “”.

<h:table xmlns:h="http://www.w3.org/TR/html4/"> <tr><td>Row1</td></tr> <tr><td>Row2</td></tr> </h:table> ================================ <r:table xmlns:h="http://www.questpond.com/restaurant/table/def"> <cloth>red</cloth> <serve>Tea</serve> </r:table>

What is the difference between xmlns and xmlns:x in WPF ?

Both the namespaces helps to define / resolved XAML UI elements.

The first namespace is the default namespace and helps to resolve overall WPF elements.

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" The second namespace is prefixed by “x:” and helps to resolve XAML language definition.


For instance for the below XAML snippet , we have two things one is the “StackPanel” and the other is “x:name”. “StackPanel” is resolved by the default namespace and the “x:name” is resolved by using “xmlns:x” namespace.

<StackPanel x:Name="myStack" />

Provide some instances where you have “xmlns:x” namespace in XAML ?

There are two common scenarios where we use “xmlns:x”name space :-

To define behind code for the XAML file using “x:class” attribute.


Second to provide name to an element.

<StackPanel x:Name="myStack" />

When should we use “x:name” vs “name” ?

There is no difference between “x:name” and “name” , “name” is short hand of “x:name”. But in classes where you do not find “name” property ( this is a rare situations) we need to use “x:name” property.

What are the different kinds of controls in WPF?

WPF controls can be categorized in to four categories:-

-Control: - This is the basic control with which you will work most of time. For example textbox, buttons etc. Now controls which are standalone control like button , text box , labels etc are termed as content control. Now there are other controls which can hold other controls, for instance itemscontrols. Itemscontrol can have multiple textbox controls, label controls etc.

-Shape: - These controls help us to create simple graphic controls like Ellipse, line, rectangle etc.

-Panel: - These controls help to align and position the controls. For instance grid helps us to align in a table manner, stack panel helps for horizontal and vertical alignment.

-Content presenter: - This control helps to place any XAML content inside it. Used when we want to add dynamic controls on a WPF screen.

All the above four types of WPF controls finally inherit from the frameworkelement class of WPF.


Can you explain the complete WPF object hierarchy?


Object: - As WPF is created using .NET so the first class from which WPF UI classes inherits is the .NET object class.

Dispatcher: - This class ensures that all WPF UI objects can be accessed directly only by the thread who own him. Other threads who do not own him have to go via the dispatcher object.

Dependency: - WPF UI elements are represented by using XAML which is XML format. At any given moment of time a WPF element is surrounded by other WPF elements and the surrounded elements can influence this element and this is possible because of this dependency class. For example if a textbox surrounded by a panel, its very much possible that the panel background color can be inherited by the textbox.

Visual: - This is the class which helps WPF UI to have their visual representation.

UI Element: - This class helps to implement features like events, input, layouting etc.

Framework element: - This class supports for templating , styles , binding , resources etc.

And finally all WPF controls textbox , button , grids and whatever you can think about from the WPF tool box inherits from the frame work element class.

Does that mean WPF has replaced DirectX?



So is XAML meant only for WPF ?





What is App.xaml in WPF project?

App.xaml is the start up file or a boot strapper file which triggers your first XAML page from your WPF project.

What are various ways of doing alignment in WPF?

There are five ways of doing alignment in WPF:-

Grid:- In Grid alignment we divide the screen in to static rows and columns like HTML tables and position elements in those rows and column area.

<Grid> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <Label Grid.Column="0" Grid.Row="0" Background="Red">1st column 1st row </Label> <Label Grid.Column="1" Grid.Row="0" Background="LightGreen">2nd Column 2nd row</Label> <Label Grid.Column="0" Grid.Row="1" Background="Red">1st column 2nd row</Label> <Label Grid.Column="1" Grid.Row="1" Background="LightGreen">2nd Column 2nd row</Label> </Grid> Stack panel :- Arranges control in vertical or horizontal format.

<StackPanel Orientation="Vertical">

<Label Background="Red">Red </Label>

<Label Background="LightGreen">Green </Label>

<Label Background="LightBlue">Blue </Label>

<Label Background="Yellow">Yellow </Label>


WrapPanel :-Aligns elements in a line until the border is hit , then wraps in to the next line.

<WrapPanel Orientation="Horizontal">

<Label Width="125" Background="Red">Red 1</Label>

<Label Width="100" Background="LightGreen">Green 1</Label>

<Label Width="125" Background="LightBlue">Blue 1</Label>

<Label Width="50" Background="Yellow">Yellow 1</Label>

<Label Width="150" Background="Orange">Orange 1</Label>

<Label Width="100" Background="Red">Red 2</Label>

<Label Width="150" Background="LightGreen">Green 2</Label>

<Label Width="75" Background="LightBlue">Blue 2</Label></WrapPanel>

Dock Panel: - Aligns controls in five different regions: top, bottom, left, right and center.


<Label DockPanel.Dock="Top" Height="100" Background="Red">Top 1</Label>

<Label DockPanel.Dock="Left" Background="LightGreen">Left</Label>

<Label DockPanel.Dock="Right" Background="LightCyan">Right</Label>

<Label DockPanel.Dock="Bottom" Background="LightBlue">Bottom</Label>

<TextBlock VerticalAlignment="Center" HorizontalAlignment="Center"> Demo of Dock panel</TextBlock>


Canvas :-Positions elements absolutely using co-ordinates.

<Canvas Margin="273,130,144,99"> <TextBlock> Canvas position </TextBlock> </Canvas>

What are resources in WPF?

Resources are objects referred in WPF XAML. In C# code when we create an object we do the following three steps :-

using CustomerNameSpace; // import the namespace. Customer obj = new Customer(); // Create object of the class Textbox1.text = obj.CustomerCode; // Bind the object with UI elements Capture.448

So even in WPF XAML to define resources which are nothing but objects we need to the above 3 steps :-

Import namespace where the class resides: - To define namespace we need to use the “xmlns” attribute as shown in the below XAML code.

<Window x:Class="LearnWpfResources.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:custns="clr-namespace:LearnWpfResources" Title="MainWindow" Height="350" Width="525">

Create object of the class :- To create an object of the class in XAML we need to create a resource by using the resource tag as the below code. You can the object name is ‘custobj”.

<Window.Resources> <custns:Customer x:Key="custobj"/> </Window.Resources> The above code you can map to something like this in C#

Customer custobj = new Customer();

Bind the object with UI objects :- Once the object is created we can then bind them using bindings like one way , two way as explained in “Explain one way, two way, one time and one way to source?” question explained above.

<TextBox Text="{Binding CustomerCode, Mode=TwoWay, Source={StaticResource custobj}}" /

When should we use static resource over dynamic resource ?

Dynamic resources reduce application performance because they are evaluated every time the resource is needed. So the best practice is use Static resource until there is a specific reason to use dynamic resource. If you want resource to be evaluated again and again then only use dynamic resource.

Explain the need of binding and commands?

WPF Binding’s helps to send / receive data between WPF objects while command helps to send and receive actions.The object that emits data or action is termed as source and the object who wants to receive data or action is termed as target.



All the above 4 things define how data will flow between target and source objects when WPF binding is applied.

Two way: - Data can flow from both source to target and from target to source.

One way: - Data flows only from source to target.

One way to source: - Data flows only from target to source.

One time: - Data flows only for the first time from source to target and after that no communication happens.


Below is an easy tabular representation to memorize the same.

One way to source

Data flow

BindingsTarget to SourceSource target
Two wayYesYes
One way to sourceYesNo
One wayNoYes
One timeNoFor first Yes


Can you explain WPF command with an example?

When end users interact with application they send actions like button click, right click , control + c, control + v etc. A command class in WPF wraps these end user actions in to a class so that they can be reused again and again.

WPF Command class idea is an implementation of command pattern from gang of four design pattern.

To create a command class we need to implement the “ICommand” interface. For example below is a simple command class which increments a counter class by calling “Increment” method.

public class IncrementCounter : System.Windows.Input.ICommand { private clsCounter obj; public IncrementCounter(clsCounter o) { obj = o; } public bool CanExecute(object parameter) { return true; } public event EventHandler CanExecuteChanged; public void Execute(object parameter) { obj.Increment(); } } The command class needs two implement two methods as shown in the above code:-

What to Execute (Execute) – Command class is all about wrapping actions of end users so that we can reuse them. At the end of the day Action invokes methods. Mean for instance a “btnmaths_click” action will invoke “Add” method of a class. The first thing we need to specify in the command class is which method you want to execute. In this case we want to call the “Increment” method of “clsCounter” class.

When to execute (CanExecute) – The second thing we need to specify is when the command can execute, means validations. This validation logic is specified in the “CanExecute” function. If the validation returns true then “Execute” fires or else the action has no effect.

You can see the code of “CanExecute” and “Execute” in the above code snippet.

Once you have created the “Command” class you can bind this with the button using the “Command” property as shown in the below XAML code.”CounterObj” is a resource object.

<Button Command="{Binding IncrementClick, Source={StaticResource Counterobj}}"/>

So now that the action is wrapped in to command we do not need to write method invocation code again and again in behind code, we just need to bind the command object with the WPF UI controls wherever necessary.

How does “UpdateSourceTrigger” affect bindings?

UpdateSourceTrigger” decides when the data should get updated between WPF objects that are binded. In other word should data get updated in lost focus event, in data change event etc.

There are four modes by which “UpdateSourceTrigger” can be defined:-

-Default: - If it’s a text property then data is updated during lost focus and for normal properties data updates in property change event.

-PropertyChanged: - In this setting data is updated as soon as the value is changed.

-LostFocus: - In this setting data is updated as soon as lost focus event occurs.

-Explicit: - In this setting the data is updated manually. In other words to update data between two WPF object you need to call the below code.

BindingExpression binding =txt1.GetBindingExpression(TextBox.TextProperty); binding.UpdateSource();

To set “UpdateSourceTrigger” we need to use the “UpdateSourceTrigger” value which can be found in the bindings properties as shown in the below figure.


Explain the need of “INotifyPropertyChanged” interface?

When we bind two WPF objects the target data is updated depending on the “UpdateSourceTrigger” events. Please refer the previous question for “UpdateSourceTrigger” basics.

The “UpdateSourceTrigger” has events like lostfocus , property change etc. In other words when lost focus or property change event happen on the target it makes a PULL to the source to get the latest data.


So it’s very much possible that the WPF source data has changed and because the WPF target “UpdateSourceTrigger” event did not fire he did not make a pull and the data of the source is not in synch with the target. This is where “INotifyPropertyChanged” interface comes to use.


Below is a simple “clsCounter” class which has a “Counter” property and this property is incremented by “Increment” method.

Now if we bind WPF label or textbox to the “Counter” property and call the “Increment” method the new “Counter” value will not be propagated to the target. Because invoking a method does not trigger any “UpdateSourceTrigger” event.

So after calling the “Increment” method the “Counter” value of the source and the target are out of synch.

So create a push event from the source you need to first implement “INotifyPropertyChanged” interface as shown in the below figure. Now when someone calls the “Increment” method you can raise an event saying that the “Counter” property has changed by calling “PropertyChanged” function as shown in the below code.

In simple words the source sends a notification to the target WPF object that data has changed in the source and he should refresh himself with the fresh data.

PropertyChanged(this, new PropertyChangedEventArgs("Counter")); Below is full “clsCounter” class code with “INotifyPropertyChanged” implemented.

public class clsCounter : INotifyPropertyChanged { private int _Counter=0; public int Counter { get { return _Counter; } } public void Increment() { _Counter++; PropertyChanged(this, new PropertyChangedEventArgs("Counter")); } public event PropertyChangedEventHandler PropertyChanged; }

What are value converters in WPF?

Binding is one of the big features in WPF which helps us to facilitate data flow between WPF UI and Object. But when data flows from source to UI or vice-versa using these bindings we need to convert data from one format to other format. For instance let’s say we have a “Person” object with a married string property.


Let’s assume that this “married” property is binded with a check box. So if the text is “Married” it should return true so that the option check box look’s checked. If the text is “Unmarried” it should return false so that the option check box looks unchecked.

In simple words we need to do data transformation. This is possible by using “Value Converters”. In order to implement value converters we need to inherit from “IValueConverted” interface and implement two methods “Convert” and “ConvertBack”.

public class MaritalConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { string married = (string)value; if (married == "Married") { return true; } else { return false; } } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { bool married = (bool)value; if (married) { return "Married"; } else { return "UnMarried"; } } } You can see in the “Convert” function we have written logic to transform “Married” to true and from “Unmarried” to false. In the “Convertback” function we have implemented the reverse logic.

Explain multi binding and multi value converters in WPF?

“MultiBinding” helps you bind multiple sources to a target while multi-converters acts like bridge if the source and targets have different data formats or need some conversion.


For example let’s say you have two textboxes which has “FirstName” and “LastName”. You want that as soon as users type on these two textboxes, the other text box should get updated with “FirstNameLastName” ( As shown in the below figure).

Also vice versa if we type in the third text box “FirstNameLastName” it should display “FirstName” and “LastName’ in the other two textboxes respectively.


So the first thing is to create a multivalue converter class which will join “FirstName” and “LastName” in to source and split “FirstNameLastName” back to target. For the same we need to implement “IMultiValueConverter” and implement “Convert” and “ConvertBack” methods.

“Convert” helps to do conversion from “Target” to “Source” and “ConvertBack” helps to convert from “Source” to “Target”.

public class NameMultiConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { // Conversion logic from Target to Source } } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { // Conversion logic from Source to Target. } }

Below is the “Convert” ( Target to Source) implementation where we get the “textbox” value in a array and we have concatenated the array values and returned the same in a single string. This single string will be displayed in the third textbox.


System.Globalization.CultureInfo culture)


string x = ""; foreach (object y in values)


x = x + " " + y.ToString();


return x;


“ConvertBack” helps to implement conversion logic from “Source” to “Target”. So when someone types “Shiv Koirala” in the third text box we would like to split “Shiv” in one string and “Koirala” in other string.

So you can see in the below code we have used the “Split” function to create a string array. So the first array index ( array[0]) will go to the first textbox and the second array index (array[1]) will go to the second text box.


public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { string str = (string)value; string[] val = str.Split(' '); return val; }

Now once we are done with the converter next thing is to apply multi-binding. Below is the XAML code where we have the three text boxes “txtFirstName” , “txtLastName” and “txtFirstAndLast”.

You can see how the “txtFirstAndLast” textbox “Text” is binded using multibinding element which binds to “txtFirstName” and “txtLastName” textbox . So now if you make changes to multiple target the single source gets updated and if you update the source multiple target gets updates.

<TextBox x:Name="txtFirstName" HorizontalAlignment="Left" Height="26" Margin="42,67,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="152"/> <TextBox x:Name="txtLastName" HorizontalAlignment="Left" Height="26" Margin="41,135,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="153"/> <TextBox x:Name="txtFirstAndLast" Height="28" HorizontalAlignment="Left" Margin="239,103,0,0" Name="label1" VerticalAlignment="Top" Width="117"> <TextBox.Text> <MultiBinding Converter="{StaticResource NameMultiConverter}"> <Binding ElementName="txtFirstName" Path="Text" /> <Binding ElementName="txtLastName" Path="Text" /> </MultiBinding> </TextBox.Text> </TextBox>

Explain WPF relative binding / relative resource?

When we define bindings we need at least two elements target and source. But many times rather than defining binding between two elements we would like to define binding with reference to the current element i.e. RELATIVELY.

For instance let’s say we have a WPF border and we would like height and width of the broder to be same. So for this scenario the target and source are the same, the WPF border itself. So we can define the binding using “RelativeSource” as shown in the below code. You can see it uses “Self” binding mode to bind the element to itself.

What are the different ways of binding using relative source?

There are four ways of binding relatively in WPF :-




-Templated parent

Can you explain self relative source binding in WPF?

This relative binding helps to bind to one property of an element to the other property of the same element. For example in the below XAML the border width is binded to height of the same border element.

<Border BorderBrush="Black" BorderThickness="1" Height="139" Width="{Binding Height, RelativeSource={RelativeSource Self}}"/>

What are styles in WPF?

WPF style helps to define look and feel ( color , fonts, alignments etc) from a central location so that we can have ease of maintenance.For more details on WPF styles please check this link out which also has simple sample WPF examples

What are style triggers?

Many times we would want a style property to execute under certain conditions. Trigger’s help you to define condition under which the style values will be set.

For instance in the below XAML code we have style trigger defined for button which set’s background color to “Red” if there is focus on the button or else the back ground color is set to “Aqua”.

<Style x:Key="myStyle" TargetType="Button"> <Style.Triggers> <Trigger Property="IsFocused" Value="True"> <Setter Property="Background" Value="Red"/> </Trigger> </Style.Triggers> <Setter Property="Background" Value="Aqua" /> </Style>

What is MVVM?

MVVM is an architecture pattern where we divide the project in to three logical layers and every layer has its own responsibility.


Below are the three logical layers with explanation what they do:-

-View: - This layer handles responsibility of taking inputs from end user, positioning of controls, look and feel, design, visuals, colors etc.

-Model: - This layer represents your middle layer objects like customer, supplier etc. It handles business logic and interaction with data access layer.

-View Model: - View model as it says View plus model represents your user interface. You can also visualize this class as the behind code. This class is the bridge between model and view. It handles connection logic , data transformation logic and action mapping between model and view. For example it will have following types of logics as shown below :-

-Replicating and propagating data between views and models. When someone enters data in to UI or the model gets updated this layer will ensure that the propagation of data happens between these entities.

-Handling data transformation from view to model and vice versa. For example you have a model which has gender property with data as “M” for male and “F” for female. But on the View or UI you would like to display as a check box with true and false. This transformation logic is written in the view model class.

-View model also map UI actions to methods. For example you have “btn_Add” click event and when any one clicks on this button you would like to invoke “Customer.Add()” method from the customer class. This connection code is again a part if view model.

What are the benefits of MVVM?

Below are the benefits of MVVM pattern:-

Separation of concern: - As the project is divided in to layers, every layer handles its own responsibility. This leads to better maintenance because when we change one layer the other layer does not get affected.

Increased UI Reusability: - The whole point of MVVM is to remove behind code i.e. XAML.CS code. The problem with behind code is that it is tied up with a UI technology for example ASPX.CS code is tied up with the ASP page class, XAML.CS file is tied with WPF UI technology and so on. So we cannot use ASPX.CS behind code with WPF XAML UI.

By moving the behind code to the view model class we can now use this with any UI technology.


Automated UI Unit testing: - View model class represents your UI. The properties of the class represent UI text boxes, combo boxes and the methods of the class represent action. Now as the UI is represented by the view model class, we can do automated UI testing using unit testing by creating the objects of view model class and doing the necessary asserts.

What is the importance of command and bindings in MVVM pattern?

MVVM in the most used architecture because of command and bindings facility provided by WPF. WPF MVVM is incomplete without command and bindings.


Command and bindings helps you to connect view (WPF UI) with view model class without writing lot of behind code. Binding connects the UI input elements (textbox, combo box etc.) with the view model class properties and the UI actions like button click, right click are connected to the methods of the class by commands.

What is the difference between MVVM and 3 layer architecture?

MVVM has an extra layer as compared to 3 layer architecture. In 3 layer architecture we have UI (view) , business logic ( model) and Data access layer ( DAL). In MVVM we have an extra layer in between view and model i.e. the view model class.

3 layer architecture complements MVVM architecture.


Explain delegate command?

First let us answer in short: - “Delegate command makes a MVVM command class independent of the view model”.Now let’s understand the long way.

In MVVM architecture view talks with the view model and view model talks with the model. When actions are sent from the view they are sent to WPF commands for handling the events. WPF commands invoked methods of view model internally.

In other words command needs reference of view model class.


If you see a typical WPF MVVM command it looks as shown below. You can see the “CustomerViewModel” class referenced inside the ‘btn Command” class. If you think with your eyes closed this reference of “Customer ViewModel” class inside the command is a problem. This will lead to tight coupling between command classes and view model.

If you visualize command it is nothing but click , double click , left mouse click , drag and drop etc. It’s an ACTION created by the user. Now wouldn’t be great if we can just attach this command with any view model. So like click event gets connected with “CustomerViewModel” or “SupplierViewModel”.

This is achieved by using delegate command.

public class btnCommand : ICommand { Private CustomerViewModel Viewobj = new CustomerViewModel(); public btnCommand(CustomerViewModel obj) { Viewobj = obj; } public bool CanExecute(object parameter) // When he should execute { return Viewobj.IsValid(); } public void Execute(object parameter) // What to execute { ViewObj.Add(); } }

To decouple the view model class from command we can use delegates i.e. “Action” and “Func”. If you see the command class we need only two things “WhattoExecute” and “WhentoExecute”. So how about passing these methods as generic delegates. You can see the constructor of “btnCommand” takes two delegates one what to execute and when to execute.

You can see in the below code the “btnCommand” class has no reference of the view model class but has references to delegates which are just abstract pointer to functions / methods. So this command class can now be attached with any view model class. This approach is termed as “Delegate command”.

public class btnCommand : ICommand // Step 1 :- Create command { private Action WhattoExecute; private Func<bool> WhentoExecute; public btnCommand(Action What , Func<bool> When) { WhattoExecute = What; WhentoExecute = When; } public bool CanExecute(object parameter) // When he should execute { return WhentoExecute(); } public void Execute(object parameter) // What to execute { WhattoExecute(); } }

What are benefits of PRISM?

Modular development: - As we are developing components as independent units we can assign these units to different developers and do modular parallel development. With parallel development project will be delivered faster.

High reusability: - As the components are developed in individual units we can plug them using PRISM and create composed UI in an easy way.

How are individual units combined into a single unit?

PRISM uses dependency injection for the same. Please see design pattern section to read about DI (dependency injection). We can do DI by two way’s by using unity application block or MEF ( managed extensibility framework).


The prime focus of PRISM is modular development and not MVVM. But it does have readymade classes like delegate command which can help us reduce MVVM code. But please note the main goal of PRISM was not MVVM.

Is PRISM a part of WPF?

No, PRISM is a separate installation.

What is expression blend?

Expression blend is a designing tool for WPF and SilverLight application.