WPF Interview Questions
The invention of computers and their infinite applications have changed and improved our lives. As a result, today's market values employees with extensive knowledge of the latest advancements in their respective fields. Desktop applications are a major part of the information technology industry. This is where WPF (Windows Presentation Foundation) comes into play since it is a powerful tool for building desktop client applications.
What is WPF?
WPF (Windows Presentation Foundation) is a new form of .NET technology developed by Microsoft that is used to build desktop applications for Windows OS. Currently, it is the latest Windows presentation API. WPF provides an extra boost in terms of animation, rich user interface, and more to application development. It is considered a vital tool for application developers. A comprehensive set of built-in features are available in WPF, including controls, application model, data binding, layout, 2D and 3D graphics, animation, styles, templates, documents, resources, typography, etc., for application development.
WPF Interview Questions for Freshers
1. When working with 3D, what namespace is needed?
Working with 3D requires the namespace System.Windows.Media.Medi3D. It provides classes that support 3-D display in Windows Presentation Foundation (WPF) applications such as AffineTransform3D, AmbientLight, DiffuseMaterial, etc.
2. What are the important features of using WPF?
The following are a few important features of WPF:
- It uses XAML (Extensible Application Markup Language) to build user interfaces for Windows applications. It allows visual designers to create UI (User Interface) elements, data binding, and events.
- WPF includes user controls such as sliders, checkboxes, and buttons necessary for developing desktop client applications.
- Furthermore, it offers data binding capabilities and supports multimedia integration.
- WPF provides an easy-to-use graphical display system for Windows.
- You can create your own custom UI controls with unlimited possibilities and flexibility.
- A variety of animations and special effects can be added to the controls and UI elements on the screen.
- A flow document model is supported which allows "desktop publishing" layout features.
- Smooth graphical effects, like color gradients and drop shadows, are possible.
- It uses hardware acceleration for rendering GUI (Graphical User Interface) to improve performance.
- The WPF applications are screen resolution-independent so you can create WPF applications that support a variety of screen resolutions.
3. Explain why we need WPF when we have windows forms.
A to G characters can better explain the need for WPF as follows:
- A - Executable on any platform (Windows or Web)
- B - Simple binding (no coding required)
- C - Standardized look and feel (resources, styles, etc.)
- D - Declarative programming (XAML)
- E - Expression Blend animation (Animation easiness)
- F - Hardware acceleration (Fast performance)
- G - Hardware-independent graphics (independent of resolution)
4. Is it true that WPF has replaced DirectX?
No, there is no substitute for DirectX because cutting-edge games still require DirectX. DirectX still offers vastly superior video performance than WPF API. In other words, DirectX will always be preferred over WPF when it comes to game development. Although you can make a game like Tic Tac Toe with WPF, you won't be able to make one with high-action animations. Remember that WPF is designed to replace WindowsForms and not DirectX.
5. Name the different types of documents supported by WPF.
Microsoft's Windows Presentation Foundation (WPF) supports the following types of documents:
- Flow format: This format alters the content based on the size of the screen.
- Fixed Format document: A fixed format document presents content regardless of the size of the screen.
6. Describe CustomControl.
The ability to create custom controls in WPF applications makes it much easier to create flexible and feature-rich controls. You can use custom controls if Microsoft's built-in controls do not meet your requirements or if you do not wish to pay for third-party controls. Basically, a custom control has its own theme, style, and template, which is defined in generic.xaml. There are several scenarios where custom controls are used:
- If you need to create the control from scratch since it does not exist.
- If you want to add extra functionality or property to a pre-existing control to meet your specific needs.
- If you need to customize and style your controls.
7. What is BAML in WPF?
XAML (Extensible Application Markup Language) is used by WPF to build user interfaces for Windows applications. XAML files are very powerful, but parsing them at runtime is rather expensive. Therefore, the MarkupCompiler converts XAML into BAML (Binary Application Markup File), which is a more compact binary version. BAML files can be generated from XAML files with the '.BAML’ extension and embedded into .NET Framework assemblies as resources. BAML is a compressed declarative language that loads and parses faster than XAML.
8. Explain freezable objects in WPF.
Freezable objects are special types of objects with two states i.e., unfrozen and frozen. Objects in a frozen state cannot be modified, whereas objects in an unfrozen state can be modified as normal objects. Freezables provide observers with a Changed event that indicates any modifications to the object. When an object is frozen, it no longer needs to handle change notifications, which can improve its performance. Freezables can be shared across threads when they're frozen, but they can't be shared when they're unfrozen. Brushes, transformations, geometries, pens, and animations are some examples of freezable objects.
Objects in a 'frozen' state cannot be altered anytime.
Let's consider a brush in a frozen state. What happens when we modify it?
SolidColorBrush myBrush = new SolidColorBrush(Colors.Blue;
myBrush.Freeze(); // Make the brush non-modifiable.
myBrush.Color = Colors.Green; // Attempting to modify frozen brush
As shown below, it throws an InvalidOperationException:
9. What do you mean by xmlns and xmlns:x in WPF?
XAML (Extensible Application Markup Language) UI elements can be defined/resolved using the xmlns and xmlns:x namespaces. As the default namespace, xmlns aids in resolving all WPF elements. XAML language definitions are resolved using the xmlns:x namespace. This is prefixed by the “x:” character.
- xmlns Example:
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x Example:
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
A good example is the XAML snippet below, in which there are 2 elements - "StackPanel" and "X:name". A "StackPanel" element is resolved using the default namespace and an "x:name" element using the "xmlns:x" namespace.
<StackPanel x:Name="myStack" />
10. Why layout panels are needed in WPF and write its different types?
GUI elements are arranged in an application by layout panels. In the event that you design your controls on fixed coordinates, the application model will not work if you move it to a different environment with different resolutions. As a result, layout panels are necessary to ensure that your control fits different screen sizes. WPF offers the following layout panels:
- Stack Panel
- Virtualizing Stack Panel
- Grid Panel
- Canvas Panel
- Dock Panel
- Wrap Panel
Consequently, these panels are easy to use, versatile, and extensible enough to meet the needs of most applications.
11. Explain triggers and write its different types.
In WPF, triggers are commonly used in Style and Control Templates. The visual effect of a WPF element is changed by triggers when a property or data changes or when an event takes place. The WPF trigger is a very important feature that allows us to modify the visual effect of controls or elements. Therefore, you are able to dynamically modify the appearance and/or behaviour of your control without creating a new one.
Triggers can be divided into three categories:
- Property Triggers: A change in one property will cause an animated or immediate change in another property.
- Data Triggers: Data triggers are triggered when certain conditions are met by bound data.
- Event Triggers: These triggers take action when a specific event occurs.
12. What do you mean by Command Design Pattern in WPF?
In object-oriented design patterns, the command pattern is one of the strongest design patterns. A command pattern refers to a design pattern that uses an object to encapsulate information required for triggering an action or event later. Method name, an object that owns the method, and the parameters of the method are among the information included here. In situations where you need to execute operations based on user requests, the command pattern is the best approach to manage objects.
WPF's command design pattern consists of the following members:
- Client: Creates a command object and sets its receiver.
- Invoker: Request command object to perform an action.
- Command: Defines the Execute operation.
- Concreate Command: Invokes the Execute operation on the receiver.
- Receiver: Executes the action requested.
13. Explain data binding in WPF.
In WPF, a mechanism called DataBinding allows data to be automatically updated between business models and user interfaces. Data binding enables WPF applications to present and access data in a consistent and simple way. In data binding, a connection is established between the application UI (User Interface) and the data that the application displays. When a binding is established, changes to data in the business model are automatically reflected in the UI elements that are bound to it and vice versa. In WPF, this is the most preferred method of getting data to the user interface.
Source properties of a data binding can be either normal .NET properties or DependencyProperties, but target properties must always be DependencyProperties.
14. Explain the different types of resources available in WPF.
Resources can be classified into two types:
- Static Resource: Resources with this type are only evaluated once at the time of XAML loading. Resources that are static are evaluated only once, and if they change after that, those changes aren't reflected in the binding. They can't be modified at runtime and remains the same (static) throughout the life of the application.
- Dynamic Resource: This is a resource that we use when we need to change the value of a property during execution. It is evaluated each time the resource is needed. When you change the code behind a resource, the elements that refer to it as a dynamic resource will also change.
Example: If you implement "bitmapImageResource" as a static resource, it will remain the same, even if the source of the image is changed. However, if you use "textForeColorResource" as a dynamic resource and change its color at runtime, then any element which references this resource will be affected.
15. What do you mean by resources in WPF?
In WPF, a resource is a type of object that you can reuse across multiple places. The resource concept provides a simple way for objects and values to be reused. For instance, you can use resources such as styles, brushes, bitmap images, etc., in various places within your WPF application. A unique key is assigned to each resource so it can be referenced from other parts of the application. The WPF resources allow you to set properties of several controls at once. The background property can be set for multiple elements in a WPF application using a single resource, for example. Resources can be declared at:
- WPF Resource declaration can be done at the application level in App.xaml.
- In addition, WPF Resources can be declared at the Window/User Control level or at the Panel level.
- In the event that your resource provisioning needs grow, then you can declare them in a separate file called a Resource Dictionary that you can refer to at the application level or any other level you desire.
16. Explain Content Alignment in WPF?
You can change the alignment of text in text boxes and buttons using content alignment. The content of content controls can be controlled by a number of properties in WPF. Two of these properties are:
- HorizontalContentAlignment
- VerticalContentAlignment
System.Windows.Controls.Control, the parent class for all WPF controls, defines these properties.
Example:
Suppose you want to create a UI (User Interface) with a Button and TextBox. The default vertical/horizontal alignment of a button's content is center, while the default vertical/horizontal alignment of a TextBox is top and left, as shown below.
But what if you want TextBoxes and Button contents positioned differently? Let's say you want to place the content of the Button and TextBox right and bottom, respectively.
VerticalContentAlignment and HorizontalContentAlignment properties are set to bottom and right, respectively, in the following code.
<Grid Name="StackPanel1" Background="LightGray" >
<Button Name="Button1" Background="LightBlue" Height="45"
Content="Click Me!" Margin="23,12,159,0" VerticalAlignment="Top"
FontSize="16" FontWeight="Bold"
VerticalContentAlignment="Bottom" HorizontalContentAlignment="Right" />
<TextBox Height="50" Margin="26,72,74,0" Name="textBox1" VerticalAlignment="Top"
Text="I am a TextBox" FontSize="16"
VerticalContentAlignment="Bottom" HorizontalContentAlignment="Right" />
</Grid>
It produces output similar to that shown below. You can see that the content in the TextBox and Button are aligned to the right and bottom, respectively.
WPF Interview Questions for Experienced
1. Explain path animation in WPF.
In Path animations, an animated object follows a path set by a Path geometry. The PathGeometry property of the PathAnimation can be set by defining a geometric path. You can use path animations to animate objects along a complex path. A complex animation can be created by joining together straight lines, arcs, and Bezier curves in any order.
Conclusion
Microsoft's WPF is the best way to develop Windows-based applications, and that will likely continue to be true in the future. As of now, a lot of companies have heavily invested in the WPF infrastructure, so they are reluctant to invest in something else. Whether you are new to WPF architecture or have experience with it, you will need to keep certain basic concepts in mind before you go to an interview. When you are interviewing for a software development job, employers will probably ask you several questions to demonstrate your WPF expertise.
In this article, we have prepared a list of 30+ WPF interview questions that will help you prepare for your WPF interview. The answers to each question are based on extensive research and tailored to meet the expectations of the interviewer.
Additional Useful Resources:
2. Can you explain what is the Prism framework in WPF?
Prism, also known as Composite Application Guidance/Library, is a framework that enables you to design and develop rich, loosely coupled, flexible, testable, and easy-to-maintain desktop applications, Silverlight Rich Internet Applications (RIAs), and Windows Phone applications. Using modular development, the client application can be developed in a way that simplifies the complexity of a large application. Applications built with Prism are composed of modules, which are reusable functional units that contain a portion of the application's overall functionality. As modules can be developed, tested, and deployed individually, cross-team dependencies can be minimized, and team members can focus on specific aspects of a project.
Major Components of Prism:
- Shell: It serves as a showcase for all modules. You can load all modules here.
- BootStrapper: It is responsible for connecting the modules to Shell.
- Modules: There are reusable functional units that can be developed independently. MVVM design patterns should be used to build these modules.
All the applications modules (A, B, C, and D as shown in the above diagram) are loaded in shell and the bootstrapper is responsible for connecting the modules to the shell.
3. State difference between Silverlight and WPF Browser application.
Microsoft offers two different products - Silverlight and Windows Presentation Foundation (WPF). These products differ in the following way:
Silverlight | WPF |
---|---|
Silverlight is a Microsoft technology that develops rich web-based internet applications. | WPF is the latest development technology from Microsoft that enables the development of enhanced graphics applications for Windows. |
It is usually regarded as a subset of WPF. | WPF is typically regarded as a subset of the .NET Framework. |
Rich Internet Applications (RIA) can be developed with Silverlight for web clients. | Rich Windows Graphical User Interfaces (GUIs) for Windows clients can be developed using WPF. |
Only direct and bubble events can be handled by Silverlight. | There are three types of routed events supported by WPF (direct, bubbling, and tunneling). |
XmlDataProvider is supported by Silverlight, but not ObjectDataProvider. | Both XMLDataProvider and ObjectDataProvider are supported by WPF. |
It does not support multibinding (taking multiple values and combining them into another value). | It supports multibinding. |
4. What do you mean by templates in WPF?
WPF templates define the overall visual appearance and look of a control. There is always a default template associated with each control, which determines how it looks. If you need to customize the visual behaviour of control or the visual appearance of it, you can easily create your own templates in WPF applications. Through data binding, the programming logic and the template can be connected. Following is a list of four types of templates:
- Control Template: It enables you to customize a control's appearance and behavior.
- Data Template: You can customize the look and feel of all your data objects with this.
- ItemsPanel Template: This template allows you to customize the layout of items in ItemControls such as ListBoxes and ListViews.
- HierarchalData Template: This template lets you customize the template of both the parent and child treeview items.
5. Explain XAML in WPF and why do we need it?
The Extensible Application Markup Language (XAML) by Microsoft is a new declarative programming language designed to create user interfaces for managed applications. WPF uses XAML to construct GUI (Graphical User Interface) for Windows applications. XAML is a markup language designed for creating user interfaces that look like XML (Extensible Markup Language). XAML is optional (in terms of usage), but it serves as the core of the WPF UI design.
Advantages of XAML-
- Designing UI elements with XAML is another simple and easy task.
- The purpose of XAML is to allow visual designers to directly design user interface elements.
- In addition to designing GUIs, it can also be used for other purposes, for example, to create workflows in Workflow Foundation.
- With XAML, you can easily create, initialize, and specify properties for objects with hierarchical relationships.
- Through XAML, WPF lets you control all visual aspects of the user interface.
- Both bitmap and vector images are supported.
- In XAML, visible UI elements can be created and separated from programming logic.
6. Explain Rotate transform in WPF.
Rotate transforms, as their name indicates, rotate an element around a specified angle. You can rotate a control, shape, or another element by certain degrees around a point by using the Rotate transform. In this way, you can create interesting user interfaces with both static and animated rotation. WPF provides a RotateTransform object that represents rotation. The Angle property indicates the degree of rotation in the clockwise direction. An element may also be rotated anticlockwise by setting a negative value. The X and Y coordinates of the center point are represented by the CenterX and CenterY properties. By default, it uses the top leftmost corner of a given element as the center point and rotates it accordingly.
Example: The following code creates two rectangles of equal size, but rotates the second rectangle by 45 degrees.
<Grid>
<!-- Original Rectangle -->
<Rectangle Width="200" Height="50" Fill="Yellow"/>
<!-- Rectangle with 45 degrees rotation -->
<Rectangle Width="200" Height="50" Fill="Blue" Opacity="0.5" Margin="61,27,117,184">
<Rectangle.RenderTransform>
<RotateTransform CenterX="-50" CenterY="50" Angle="45" />
</Rectangle.RenderTransform>
</Rectangle>
</Grid>
As you can see in the following output, the second rectangle has been rotated by 45 degrees.
7. Explain Routed Events in WPF.
Routed events are those that follow a specific routing strategy in order to move up or down the visual tree. Event handlers can be hooked up to the element that triggers the event or to multiple elements above and below it.
There are three main routing strategies for RoutedEvents, which are as follows:
- Direct Event: An event triggered by a source element that must be handled by the source element itself. Direct events behave similarly to normal .NET events.
- Bubbling Event: A bubble event begins with the element from where it was raised. Afterwards, it navigates up to the top element (root) of the visual tree or until the event bubbles are stopped by marking it as handled. Typically, the top (root) element of WPF is a window.
- Tunnel Event: The root element raises this event. Following that, it navigates down the visual tree to reach the source element of the visual tree or until the tunnelling event is terminated by marking it as handled.
8. What are Attached properties in WPF?
An attached property is a concept in XAML (Extensible Application Markup Language). Essentially, these properties enable you to assign extra properties/values to any XAML element, even if it doesn't define them in its object model. As a special type of DependencyProperty, you can apply it to any DependencyObject to enhance the behavior of various controls and services. Attached properties would be useful in the following cases:
- When parent elements iterate its child object and act upon them in a certain way. Grid controls, for example, organize elements into rows and columns using its Grid.Row, Grid.RowSpan, Grid.Column and Grid.ColumnSpan attached properties.
- When adding visuals to existing controls using custom templates.
- The addition of generic features/services to existing controls, for example, ToolTipService and FocusManager. They are called attached behaviors.
9. What are Dependency properties in WPF?
WPF dependency properties are properties that extend the functionality of CLR (Common Language Runtime) properties. Dependency properties are those whose value is dependent on external sources (value from other inputs), such as animation, data binding, styles, themes, and user preferences, or visual tree inheritance. These properties provide self-contained validation, default values, monitoring of changed properties, and other runtime information.
Advantages of Dependency Property:
- Dependency Property is not stored every time, but only when it is modified or changed. As a result, memory consumption is reduced.
- The DependencyProperty is notified whenever a property's value changes via INotifyPropertyChange. As a result, data binding becomes simpler since changes are immediately reflected in the value.
- Dependency Properties are capable of supporting animation, setting styles via style setters, and even providing control templates.
10. Can you explain value convertor in WPF?
With WPF binding, you can bind two WPF UI objects and flow data between them. Objects emitting data are called sources, and objects accepting them are called targets.
ValueConverter is a piece of code that converts values from the source type to the target type and back again, so you can databind properties that have incompatible types. A value converter implements IValueConverter, a simple interface that provides two methods: Convert() and ConvertBack(). As a bridge between the source and target, WPF converters provide a way to convert data if the target and source have different data formats.
11. Explain how MVVM (Model-View ViewModel) is different from MVC (Model-View Controller).
MVVM and MVC differ in the following ways:
MVVM Pattern
MVC Pattern
MVVM | MVC |
---|---|
A well-known architecture pattern for application development, MVVM stands for Model-View-ViewModel. | MVC stands for Model-View-Controller, the earliest Android application architecture. |
MVVM architecture consists of three main components: View, Model, and ViewModel. | A MVC pattern consists of three main components: Model, View, and Controller. |
A model represents an object, a view represents the UI layer, and a viewmodel describes the connection between models and views. | Models represent data, Views represent the UI, and Controllers deal with requests. |
Silverlight, AngularJS, and WPF all rely on MVVM. | Java springs and ASP.NET use MVC. |
The application is easy to modify. However, if the logic for data binding is too complex, it will make debugging the application a little more difficult. | Changing or modifying application features can be difficult due to the tight coupling of the code layers. |
This architecture has the highest level of unit testability. | A limited number of unit tests are supported. |
12. What are the important features of MVVM?
The following are some of the features of MVVM:
- MVVM allows your application architecture to be loosely coupled. A layer (Data layer, presentation layer, and domain layer) can be changed independently of others.
- The Model, ViewModel, and View layers can each be extended separately without impacting the others.
- One can write test cases for both the Model and ViewModel layers without referencing the View layer directly. As a result, it is easier to write unit test cases.
- Enhanced system performance allows screens to load more quickly.
- Code-behind files are not needed (minimalist code-behind files).
- It is possible for designers and developers to work together.
- Streamline the workflow for designers and developers.
- UI and Business layers are separated as views and viewmodels respectively.
- Make complex WPF applications easier to develop.
13. What do you mean by MVVM (Model View ViewModel)?
MVVM (Model-View-ViewModel) is a pattern that is used extensively by the Windows Presentation Framework (WPF) for building applications. MVVM is not mandatory to create WPF applications, but knowing about it can simplify the process of building WPF applications. This method allows developers and designers to work together without a great deal of technical difficulty by utilizing the capabilities of the WPF platform. There are three main components of MVVM as shown below:
- View: Views represent the user interface components of WPF applications written in XAML. A number of controls are available, including user controls, buttons, and labels. There are also resources such as ControlTemplate, DataTemplate, and Styles. Although the view may be entirely code-based, XAML will (and should) be used for a large proportion of the UI.
- Model: In general, the model provides your application with the data it needs. Models implement the model for an application domain and also include business objects, validations, and backend objects for retrieving and storing data.
- View Model: It is the interface between Views and Models, handling Presentation Logic as well as retrieving/saving data from the Models. In other words, it's an abstraction of a view in the application. ViewModels contain the logic that manipulates the raw data so that it is displayed in views.
By calling the public methods in the Model classes, the ViewModel interacts with the Model. Model data is collected and sent to the View. Using WPF's data-binding and command features, the View interacts with the ViewModel. The ViewModel implements commands that are executed whenever a user interacts with the view.
14. Difference between WPF and Winforms.
- WinForms (Windows Forms): WinForms is Microsoft's GUI (Graphical User Interface) approach to the .Net Framework and was introduced in February 2002. It was the primary API for .NET used to build Windows applications until WPF and Silverlight were introduced. In order to develop a standalone application, only the runtime environment and OS (Operating system) are required.
- WPF (Windows Presentation Foundation): In 2007, Microsoft introduced WPF to replace WinForms in desktop application development for the .Net Framework. WPF is a UI framework designed for creating Windows or desktop applications. Currently, it is the latest Windows presentation API.
Difference between WPF and Winforms:
WPF | Winforms |
---|---|
It is the latest concept for building desktop/windows applications. | This is the old way to build desktop applications for Windows. |
A markup language is used to design the UI, allowing complex user interfaces to be designed. | No markup language is used to design UI. Instead, event-driven controls are used. |
Comparatively to WinForms, it provides effective and fully supported data binding. In data binding, a connection is established between the application UI (User Interface) and the data that the application displays. | Although it offers data binding, it does so in a limited way, so it's less effective than WPF. |
Besides providing 2D and 3D vector capabilities, it also offers functionality such as rich, interactive, animated, hardware-accelerated functions. | In comparison to WPF, it does not provide rich, interactive, animated, hardware accelerated, vector 2D and 3D features. |
It is not easy to use WPF as it requires good knowledge of the controls. | When developing applications, Windows forms are more convenient. |
There is no limit to the customization of the UI, and the controls can be modified without difficulty since it is written from scratch. | It typically contains limited controls that are not easy to customize. |
This is an efficient approach when building an application that requires a variety of media types, creates a skinned user interface, binds to XML, and creates a desktop application that has a web-like navigation style. | When you want to develop a simple application with few modern features and more resources online, it is considered good. |
15. State difference between WCF (Windows Communication Foundation) and WPF (Windows Presentation Foundation).
- WCF (Windows Communication Foundation): WCF is a Microsoft unified programming technology used for creating, configuring and deploying applications to a production environment for testing purposes. Developers can use it to create secure, reliable solutions that work across multiple platforms. It deals with the interoperability of distributed applications using the .NET framework. Learn More.
- WPF (Windows Presentation Foundation): WPF is a new form of .NET technology developed by Microsoft that is used to build desktop applications and high-fidelity experiences for Windows. A comprehensive set of built-in features are available in WPF, including controls, application model, data binding, layout, 2D and 3D graphics, animation, styles, templates, documents, resources, typography, etc., for application development.
WPF MCQ
_____ are resources that you can manipulate and evaluate at runtime.
XAML stands for ___
Routed events that are supported by WPF are __
WPF stands for __
WPF is the replacement for __
Which of the following languages is used to create user interfaces in WPF?
What is the purpose of WPF?
Which of the following is not a type of layout panel in WPF?
Which of the following statements about XAML is true?
Freezable objects can exist in which of the following states?