WPF Interview Questions With Answers
WPF Interview Questions With Answers
What is WPF? .....................................................................................................................2 What is the need of WPF when we had windows forms? .....................................................2 What is XAML in WPF and why do we need it? .................................................................2 What is xmlns in XAML file ?.............................................................................................3 What is the difference between xmlns and xmlns:x in WPF ? ..............................................4 Provide some instances where you have xmlns:x namespace in XAML ? .........................4 When should we use x:name vs name ? ........................................................................5 What are the different kinds of controls in WPF?.................................................................5 Can you explain the complete WPF object hierarchy? .........................................................6 Does that mean WPF has replaced DirectX? ........................................................................8 So is XAML meant only for WPF ? .....................................................................................8 Can you explain the overall architecture of WPF? ...............................................................8 What is App.xaml in WPF project?......................................................................................9 What are resources in WPF ? ............................................................................................. 10 Explain the difference between static and dynamic resource? ............................................ 11 When should we use static resource over dynamic resource ? ............................................ 12 Explain the need of binding and commands? ..................................................................... 12 Explain one way, two way, one time and one way to source?............................................. 12 Can you explain WPF command with an example? ........................................................... 14 How does UpdateSourceTrigger affect bindings? ........................................................... 16 Explain the need of INotifyPropertyChanged interface? ................................................. 17 What are value converters in WPF? ................................................................................... 18 Explain multi binding and multivalue converters in WPF? ................................................. 20 Explain WPF relative binding / relative resource?.............................................................. 22 What are the different ways of binding using relative source? ............................................ 23 Can you explain self relative source binding in WPF? ....................................................... 23 Explain Ancestor relative source binding in WPF? ............................................................ 23 Explain the difference between visual and logical tree in WPF ?........................................ 27 Why do we need to have these perspective of visual and logical tree in WPF ? .................. 29 Explain routed events in WPF? .......................................................................................... 29 What is MVVM? ............................................................................................................... 30 What are the benefits of MVVM? ...................................................................................... 31 What is the importance of command and bindings in MVVM pattern? .............................. 32 What is the difference between MVVM and 3 layer architecture? ...................................... 32 Explain delegate command? .............................................................................................. 33 What is PRISM? ................................................................................................................ 35 What are benefits of PRISM? ............................................................................................ 35
How are individual units combined in to a single unit ? ..................................................... 36 Does PRISM do MVVM? ................................................................................................. 36 Is PRISM a part of WPF? .................................................................................................. 36 What is expression blend? ................................................................................................. 36
What is WPF?
WPF (Windows Presentation foundation) is a graphical subsystem for displaying user interfaces, documents, images, movies etc in windows application.
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)
So to avoid the same we can use XML namespaces. You can see in the below XML we have qualified the HTML table with <h:table> and the restaurant table element qualified with <r:table>.
<h:table xmlns:h="http://www.w3.org/TR/html4/"> <tr><td>Row1</td></tr> <tr><td>Row2</td></tr> </h:table>
The second namespace is prefixed by x: and helps to resolve XAML language definition.
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
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" />
All the above four types of WPF controls finally inherit from the frameworkelement class of WPF.
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 framework element class.
Figure 8.2: - Architecture of WPF Above figure shows the overall architecture of WPF. It has three major sections presentation core, presentation framework and milcore. In the same diagram we have shown how other section like direct and operating system interact with the system. So lets go section by section to understand how every section works. User32:- It decides which goes where on the screen. DirectX: - As said previously WPF uses directX internally. DirectX talks with drivers and renders the content. Milcore: - Mil stands for media integration library. This section is a unmanaged code because it acts like a bridge between WPF managed and DirectX / User32 unmanaged API. Presentation core ;- This is a low level API exposed by WPF providing features for 2D , 3D , geometry etc. Presentation framework:- This section has high level features like application controls , layouts . Content etc which helps you to build up your application.
App.xaml is the start up file or a boot strapper file which triggers your first XAML page from your WPF project.
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.
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.
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.
The above resource is binded with the below two textboxes statically and dynamically respectively.
Now if we modify the resource , you see the first text box changes the background and the other textbox color stays as it is.
Explain one way, two way, one time and one way to source?
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. Data flow Target to Source Source to target Yes Yes Yes No No Yes No For first Yes
Bindings Two way One way to source One way One time
public class IncrementCounter : System.Windows.Input.ICommand { private clsCounter obj; public IncrementCounter(clsCounter o) { obj = o; } public bool CanExecute(object parameter) { return true; }
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.
Default: - If its 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.
To set UpdateSourceTrigger we need to use the UpdateSourceTrigger value which can be found in the bindings properties as shown in the below figure.
So its 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"));
Lets 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 looks 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.
For example lets 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 FirstName LastName ( As shown in the below figure). Also vice versa if we type in the third text box FirstName LastName 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 FirstName LastName 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.
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { string x = ""; foreach (object y in values) {
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>
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 lets 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.
Now we want the background color of the text box to be binded to one of the parent border colors. To achieve the same we can use ancestor relative binding. Below are some important properties in Ancestor type binding we need to know before we writing the binding code. Property AncestorType AncestorLevel Description Which type of parent element is it?. Is it a border element , grid element etc. An element can have multiple parents. For example in the above XAML we have two parents one with red color and the other with green. So this property specifies which level of parent element we want to refer. Below is the figure which depicts the levels. The red color border is level 1 and the green color border is level 2. So the nearest element becomes the first level and so on. This specifies which property we want to bind to. For the current example we want to bind to borders brush color.
Binding
So the relative binding code with ancestor level 1 i.e. red looks as shown below. In case you are confused with any of the properties please refer to the previous table for more information.
So now the complete XAML with parent border element looks as shown in the below code.
<Border BorderBrush="DarkGreen"> <!-- Level 2 -> <Border BorderBrush="DarkRed> <!-- Level 1 -> <TextBox Background="{Binding BorderBrush, RelativeSource={RelativeSource FindAncestor, AncestorLevel=1, AncestorType={x:Type Border}}}"/>
</Border> </Border>
Now if you run the above XAML code the textbox is binded with the back ground color of the first border. If you change the ancestor level to 2 textbox background color will change to green.
PreviousData
<ItemsControl ItemsSource="{Binding}" Margin="10"> <ItemsControl.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock FontSize="14" FontWeight="bold" Margin="20" Text="{Binding Value}" Background="Aqua"> </TextBlock> <TextBlock FontSize="14" FontWeight="bold" Margin="20" Text="{Binding RelativeSource={RelativeSource PreviousData}, Path=Value}" Background="Blue"> </TextBlock> </StackPanel> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> public class Item : INotifyPropertyChanged { private double _value;
public double Value { get { return _value; } set { _value = value; OnPropertyChanged("Value"); } } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; #endregion protected void OnPropertyChanged(string PropertyName) { if (null != PropertyChanged) { PropertyChanged(this, new PropertyChangedEventArgs(PropertyName)); } } } public class Items : { public Items() { Add(new Item Add(new Item Add(new Item Add(new Item Add(new Item Add(new Item Add(new Item Add(new Item Add(new Item } } ObservableCollection<Item>
{ { { { { { { { {
= = = = = = = = =
80.23 }); 126.17 }); 130.21 }); 115.28 }); 131.21 }); 135.22 }); 120.27 }); 110.25 }); 90.20 });
</Window>
So if you visualize the above XAML logically you can think that the button control is a child element of the Grid and the grid is the child element of the Window. This relationship between the elements which looks logical looking at the XAML is termed as Logical tree.
But now to display this Logical tree on to your screen you need lot of visual elements. like border, text etc. So when you add these visual elements to the logical tree that complete structure is termed as Visual Tree. Putting in simple words there is only tree in WPF but depending on how you view it these two trees are the outcome. If you use the WPF visualizer the above XAML tree looks something as shown in the below figure which is actually a complete visual tree.
In simple words whatever you see in your XAML is a logical tree and to make it display it uses the visual tree. Below is an in detail figure which shows the logical and visual tree of the above XAML. Logical tree is without the shades and with shades is the visual tree.
Why do we need to have these perspective of visual and logical tree in WPF ?
Visual tree and Logical tree are important when you work with WPF routed events.
Bubbling events: - They travel up the visual tree hierarchy. For example MouseDown is a bubbling event. Tunneling events: - These events travel down the visual tree hierarchy. PreviewKeyDown is a tunneling event.
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.
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.
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.
If you see a typical WPF MVVM command it looks as shown below. You can see the CustomerViewModel class referenced inside the btnCommand class. If you think with your eyes closed this reference of CustomerViewModel 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. Its an ACTION created by the user. Now wouldnt 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(); }
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(); }
WhattoExecute(); } }
What is PRISM?
PRISM is a framework to develop composite application in WPF and Silverlight. Composite applications are built using composition. In other words rather than building application from scratch we take prebuilt components, assemble them together and create the application.
Take the below example of simple WPF UI. You can see it has lots of sections. Now rather than building the whole UI as one big unit, we can develop all these section as independent unit. Later by using PRISM we can compose WPF UI by taking all these independent units.