Here are the top 30 WPF Interview questions with their corresponding answers. I have provided detailed and concise answers with code samples where suited. Prepare yourself and impress your interviewer by answering the most commonly asked questions for WPF with research-backed answers.
What is WPF?
WPF stands for Windows Presentation Foundation. It is a UI framework for developing Windows desktop applications. It contains highly rich UI features and built-in support for resources, graphics, data binding and event triggers. For full description, see here.
What are the advantages and disadvantages of WPF?
Advantages
- Resolution Independence – WPF uses vector graphics to enable your applications to become resolution-independent.
- Complete multimedia integration – Previously in Windows Form, to use 3D graphics, video, speech and rich document viewing you would have to know various separate technologies and then merge them. There also wasn’t much built-in support. Now with WPF applications, you can use all the above features with one programming model.
- Makes use of GPU – WPF is built on top of Direct3D, which offloads work to graphics processing units (GPUs) rather than using CPUs. This means WPF applications make use of hardware acceleration giving rise to crisper graphics and improved performance.
- Declarative programming – WPF defines the layout of applications objects and represents 3D models using Extensible Application Markup Language (XAML) declarative programming. This enables graphic designers to directly manipulate the look and feel of WPF applications.
- Easily customizable – WPF controls are easily customizable. It is possible to not write any code to customize controls. You can also create themes for applications to drastically change the standard look.
- Culturally aware – Static text in controls are dependent on the culture and language specified by the user’s operating system.
Disadvantages
- WPF’s in-built control suite is more limited than WinForms
- Although it’s changing by time, there is more support for 3rd party controls.
- WPF is a learning curve since most developers already know WinForms
- WPF will not run on Windows 2000 or lower.
- WPF does not provide MDI child mode.
- Most developers already know WinForms; WPF provides a new learning curve.
What is the difference between WPF and Silverlight?
These are the main distinctions between the Silverlight and WPF browser application:
- .NET Framework is needed to run WPF Browser applications on the client machine while Silverlight runs only as a plug-in.
- Silverlight can be run on any OS while WPF applications run only on Windows as it depends on .NET Framework.
What is XAML?
XAML stands for Extensible Application Markup Language and is a markup language used to define objects and properties including graphical and non-graphical in XML. The documents are loaded using a XAML parser. In WPF it is used to construct the user interface.
- Create event handlers
- Define resources – allows the creation of templates, animations, centralize and standardize formatting.
- Define Control templates to change the appearance of the standard controls
XAML can be the following types:
- WPF XAML
- XPS XAML
- Silverlight XAML
Why do you use XAML?
In WPF, workflows are defined using XAML. XAML can also be used in Silverlight applications, Windows 10 Mobile and UWP apps (also known as Windows Store apps). Here are some reasons why you use XAML:
- Since XAML is based on XML, both designers and developers can share and modify the content easily between them without requiring compilation.
- XAML also has the benefit of being declarative which is easier to define the UI than procedural code is.
- XAML allows for clearer and shorter code
- Defines a separation of design and logic
- Tools such as Expression blend used for graphical design need XAML as their source
Explain what is Markup extension in XAML?
Markup Extensions are placeholders in XAML which resolve a property at runtime. The use of mark up extensions is to process a string and return an object. Some examples include x:Null, x:Array, x:StaticResource and x:DynamicResource.
What are Resources in WPF?
In WPF, resources are a way of reusing commonly defined objects and values. They also let you set properties for multiple controls at a time. For instance, if you want to set the background property to several elements, you can do so by using a single resource.
Here is the syntax of a resource:
<elementName propertyName="{markupExtension keyName}"/>
Where elementName refers to the name of the element that makes use of the resource, PropertyName takes the value of the resource, MarkupExtension defines the type of resource and keyName is the name of the resource. The keyName must be a unique string that identifies the resource. Here is an example of an element Textbox with propertyName Text using a markup extension x: Static with a key name of resx: Strings.productTitle (resx actually refers to the namespace from where Strings is found to avoid referring to the full namespace each time)
<TextBlock Name="lblProductTitle" Text="{x:Static resx:Strings.productTitle}"/>
What is the difference between Static and Dynamic Resources?
The difference between StaticResource and DynamicResource is that StaticResource evaluates the resource only once while DyanmicResources evaluates the resource each time it is required. DynamicResource is heavier on the system but it will make your pages and windows load faster.
What is a routed event?
A routed event is a type of event that is used to invoke handlers on multiple listeners inside an element tree. There are various types of elements in WPF applications and these elements are set in an element tree relationship.
There are 3 types of routed events:
- Direct – This event can only be invoked by the original element. An example of this is a MouseEnter event.
- Tunnelling – This event is triggered by the original element and then raised consecutively by each container in the visual tree until it reaches the topmost element. In WPF, in most cases, the topmost element is the Window.
- For example, let’s say you have a StackPanel that includes a button. If you click on the button, the event route will be Button > StackPanel > Window.
- Bubbling – Bubbling is the opposite of tunnelling. This event is raised by the top-most parent container in the visual tree and then is triggered by each consecutive container child until it reaches the element where the event was originated. In XAML, you will find Tunneling event names start with Preview and Bubbling events without. So in WPF, you will always find PreviewMouseDown and MouseDown Events.
For more details on how routed events work, see here.
What is a value converter in WPF?
A value converter is used to convert the type of the target and source when they have different types. For instance, if you have a ComboBox that has values filled from an Enum of type int. In this case, you want to be able to convert the integer to a string. To be able to use a Converter you need to implement IValueConverter and implement the two methods Convert and ConvertBack. You then need to refer to the Converter inside your XAML when declaring your ComboBox. See the example below.
<Grid>
<TextBlock Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="2" Margin="4" Text="{Binding FullName}" HorizontalAlignment="Center" FontWeight="Bold"/>
<TextBox Grid.Column="1" Grid.Row="1" Margin="4" Text="{Binding FirstName, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Width="200"/>
</Grid>
<local:DaysOfWeekToStringConverter x:Key="enumConverter" />
<ComboBox x:Name="CmbAppointmentDays" Style="{StaticResource UIKit.ComboBox}" SelectedValue="{Binding Source={x:Static local:App.Prefs}, Path=DaysOfWeek, Converter={StaticResource enumConverter}}" ItemsSource="{Binding Source={local:DaysOfWeekEnum}}" />
public enum DaysOfWeek
{
[Description("dayOfWeek_mon")] Monday = 1,
[Description("dayOfWeek_tues")] Tuesday = 2
}
public sealed class DaysOfWeekToStringConverter : EnumToStringConverter<DaysOfWeek>
{
}
public sealed class DaysOfWeekEnumExtension : EnumToStringExtension<DaysOfWeek>
{
}
public class EnumToStringExtension<T> : MarkupExtension where T : struct, IConvertible ...
What is MVVM and how is it applied in WPF?
MVVM is a design pattern that divides the UI code into 3 parts:
- View – It is the XAML code that defines the visual part of the application. It should not contain any logic inside the code-behind. It binds to the ViewModel by data binding.
- Model – It is responsible for exposing data in a manner that is easily consumable by WPF. It must implement INotifyPropertyChanged interface and/or the INotifyCollectionChanged interface depending on the type of data present.
- ViewModel – It is an abstraction of the view layer. It exposes data and behaviours for the views via Commands.
View
<Textblock x:Name="txtName" Content="{Binding ElementName=_this, Path=FullName}"/>
ViewModel
// INotifyPropertyChanged notifies the View of property changes, so that Bindings are updated.
sealed class MyViewModel : INotifyPropertyChanged
{
private User user;
public string FirstName
{
get {return user.FirstName;}
set {
if(user.FirstName != value)
{
user.FirstName = value;
OnPropertyChange("FirstName");
// If the first name has changed, the FullName property needs to be updated as well.
OnPropertyChange("FullName");
}
}
public string FullName
{
get { return FirstName + " " + LastName;}
}
}
sealed class User
{
public string FirstName {get;set;}
public string LastName {get;set;}
}
What are dependency properties?
Dependency properties are a particular type of property which is an extension of the CLR property. It utilizes the specific functionalities in the WPF property system. A class which defines a dependency property must inherit the DependencyObject class. Most of the UI control classes which are used in XAML are derived from DependencyObject class in fact and so they support dependency properties. Some examples include the Button class which supports IsMouseOver dependency property.
<Grid> <Button Margin = "5" Content = "Click Me!"> <Button.Style> <Style TargetType = "{x:Type Button}"> <Style.Triggers> <Trigger Property = "IsMouseOver" Value = "True"> <Setter Property = "Background" Value = "Blue" /> </Trigger> </Style.Triggers> </Style> </Button.Style> </Button> </Grid>
Dependency properties are used if you want to set a style, create a data binding, set an element with a resource (static or dynamic) or if you want to add animation. Dependency properties are stored in a dictionary of key/value pairs provided by the DependencyObject class. It saves on memory because the property is only saved when there is change. Unlike CLR properties which read and write directly from the private member of a class and are stored in the local object. That is why Dependency Properties have an advantage over regular CLR properties and that is why they are used in UI.
Explain what View and ViewModel is in WPF
View in WPF
The View is the user interface that collates all the elements of the window, navigation page, user control, resource files, styles, themes and custom tools and controls. The View is independent of the ViewModel and Model and vice versa and is tightly decoupled.
However, the ViewModel is aware of the needs of the view. They communicate with the use of data binding and dependency properties.
What is Data Binding and how is it applied in WPF?
Data Binding allows you to extract information from one object to another and display it in one or more elements in the UI. It is the most powerful feature for XAML compared with other traditional web technologies in NET. XAML gives the ability to bind any property to any element or object or data source. It allows you to extract data from some dependency property or object and bind it to another dependency property or object or directly to an element.
These are the most common data bindings used in WPF:
One-way Binding
In One-way binding, the data is bound from its data source to its data target.
<TextBox Name=”txtAge” Text=”{Binding Age, Mode=”OneWay}”/>
If the user changes the age in the textbox, the binding will remain the same.
Two-way Binding
For Two-way binding, the data can be modified from the user interface by the user which is then updated in the data source. If the source changes while the user is viewing the interface, you want that the view is updated too. To add a two-way binding you use the following syntax:
<TextBox Name=”txtAge” Text=”{Binding Age, Mode=”TwoWay}”/>
If the user changes the age in the textbox, the binding will change the data source.
Name the different binding modes in WPF
There are 4 types of binding modes in WPF. If you do not specify any mode, the behaviour will depend on the particular control you use:
- OneWay – This is used when you want to bind your property to update the user interface.
- TwoWay – This has the same effect as OneWay and OneWayToSource combined. The bound property will update the user interface but changes in the user interface will also update the bound property. This is useful for text boxes or checkboxes since it requires user interaction.
- OneTime – This acts the same as OneWay except that it will only update the user interface once. It is actually recommended that you use this binding as the default unless you explicitly require the above functionality.
- OneWayToSource – This does the opposite of OneWay binding mode. The user interface value changes the bound property. Remember that in OneWay, the bound property changes the interface.
Why does UpdateSourceTrigger influence bindings?
This property is used in two-way binding. It is a property on a binding that controls that data flow from the data target to a data source. The default source trigger change is when the focus is lost but other properties use UpdateSourceTrigger:
LostFocus: This value is updated when the focus is no longer on the control.
PropertyChanged: This occurs whenever the target property value changes. For example, in a textbox, its when a keystroke occurs.
Explicit: Used to stop source updates until the user actually acts explicitly, like clicking on a button.
<TextBox Name="txtTarget" Width="2oo" Height="30"
Text="{Binding ElementName=SourceText, Path=Text,UpdateSourceTrigger=Default}"/>
What is a trigger? Name the different types of Triggers
What is Prism?
Prism is composite application guidance for WPF and Silverlight and is design to build applications that have a single code base. It aims to develop a complex large application into simpler modules using a modular fashion. It provides help in applying patterns and practices developed by Microsoft to help design robust, flexible and maintainable WPF applications.
For details on what each module does, see here.
What are templates in WPF?
Templates form an important part of the user interface in WPF. WPF has 3 types of templates: Control, Items Panel and Data Templates.
Control Template
The ControlTemplate is used to change or create a new appearance of controls. The look and appearance of control can be changed or redefined by changing the ControlTemplate of a control. ControlTemplate is most useful when you want to create your own custom controls. For example, you can choose to create a custom button that has circular borders. Templates are defined as resources inside the FrameworkElement’s Resources Property.
<Grid.Resources>
<ControlTemplate x:Key="CircularButtonTemplate">
<Grid>
<Ellipse Width="200" Height="200" x:Name="CircularButton" Fill="Blue" />
<Ellipse Width="180" Height="180" Fill="Green" />
</Grid>
</ControlTemplate>
</Grid.Resources>
Items Panel Template
This template is used when you want to group resources and event handlers for any FrameworkElement. Styles are resources and can be used as any other resource and can be applied to any part of the visual tree – i.e. the root, parent element, current element or on an application level. The scope of styles works in a bottom-up approach – first, it attempts to find the style locally, and if not found, it traverses up to the parent element in the visual tree until it reaches the root. The styles can be found in application and themes.
A style contains Setter tags in this form: <Style> <Setter></Setter>…</Style>
Each setter contains a property and a value. The property is the name of the property and the value is the property value of the element to which the style will be applied.
<Grid>
<Grid.Resources>
<Style TargetType="{x:Type Button}">
<Setter Property="Width" Value="150"/>
<Setter Property="Margin" Value="10"/>
<Setter Property="Foreground" Value="Black"/>
<Setter Property="Background" Value="White"/>
<Setter Property="BorderBrush" Value="Black"/>
<EventSetter Event="Click" Handler="Button_Click"/>
</Style>
</Grid.Resources>
<Button>Click me</Button>
</Grid>
Data Template
A DataTemplate is used to apply visualisation to your data objects. They are particularly useful when you want to bind an entire collection of a ListBox. In this case you can use a DataTemplate to define the appearance for each specific item. In this way, the content for your DataTemplate becomes the visual structure of your data objects. A data template is also useful when you want to reuse components that have data that can be supplied from different sources
<DataTemplate x:Key="fileInfoTemplate">
<StackPanel>
<TextBlock Text="{Binding Path=FileName}" />
<TextBlock Text="{Binding Path=FilePath}"/>
<TextBlock Text="{Binding Path=FileSize}"/>
</StackPanel>
</DataTemplate>
....
//Reference data template
<ListBox Width="500" Margin="10" ItemsSource="{Binding Source={StaticResource fileList}}" ItemTemplate="{StaticResource fileInfoTemplate}"/>
-
How can you apply animation in WPF? Mention some examples.
- WPF animations work with a timing system and work by applying dynamic visualisations on properties. For example, if you require an element to grow, then you can animate their Width and Height properties. If you want an element to fade from view, then you can animate its Opacity property.
- For a property to have animation capabilities, it must have the following requirements:
- It must be a dependency property
- It must be part of a class that inherits DependencyObject and implements IAnimatable interface.
- It must have a compatible animation type. However, if it does not have, you can create your own using Custom Animations Overview
- The majority of objects have IAnimatable properties. Some examples include controls such as buttons, TabControl, Panel and Shape objects which all contain objects that inherit DependencyObject.
- Animations can be used anywhere including styles and control templates.
- Animations do not need to be visual, you can also animate objects that are not part of the UI if they meet the above criteria described in the second point.
Here is an example of a Fade-in Fade-out of a Rectangle
<Rectangle Name="AnimateRect" Width="100" Height="100" Fill="Blue">
<Rectangle.Triggers>
<!--Animates using the opacity property in 10 second intervals and keeps repeating -->
<EventTrigger RoutedEvent="Rectangle.Loaded">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="AnimateRect" Storyboard.TargetProperty="Opacity"
From="1.0" To="0.0" Duration="0:0:10" AutoReverse="True" RepeatBehavior="Forever" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Rectangle.Triggers>
</Rectangle>
Some more common examples include ColorAnimation to animate a colour in an element, DoubleAnimation to change width/height, PointAnimation to animate the centre of an ellipse, and StringAnimation to animate the text in a text control.
What are the different types of layouts you can use in XAML?
Layouts are used to order a group of UI elements in the application. There are different layouts and therefore it’s important to keep in mind the following when choosing the best layout: The positions and sizes of the child elements and the layering of overlapping child elements on top of each other.
Due to screen resolution differences, it’s never a good idea to use fixed pixel arrangements. That is why the XAML provides built-in layouts that can help accommodate this.
Some of the commonly used layouts are the following:
Stack Panel | Stack Panel is the most simple and useful layout in XAML. With a stack panel, the child elements can be placed in a single line either horizontally or vertically based on the orientation property. |
Wrap Panel | With a WrapPanel, the child elements are positioned sequentially either left-right or top-bottom based on the orientation property. If an element does not fit, it will wrap to the next row or column accordingly. |
Dock Panel | DockPanel is used when you define the areas where your child elements will be relative to each other (horizontally/vertically). You can dock child elements in top, bottom, right, left or centre using the Dock Property. |
Canvas Panel | Canvas panel is the most basic layout panel where child elements are positioned using coordinates relative to the Canvas. |
Grid Panel | A Grid Panel gives the most flexibility in the positioning of child elements since the area is split into rows and columns and so the elements can be arranged in a tabular form. |
What are WPF Content controls?
The Content controls form part of the ContentControl class and they represent controls that include a singular item of content. This content is usually in the form of plain text or child control. The ContentControl inherits the Control class in WPF. The below example demonstrates different controls that are Content Controls. Note how the Content can be set in different ways. Either as the value inside the tags or as an attribute.
<StackPanel>
<ScrollViewer Background="White" Content="Content as an attribute"/>
<ScrollViewer Background="Blue">Content Text as value between tags</ScrollViewer>
<ScrollViewer Background="Red">
<Button Margin="30 5">Button with content text</Button>
</ScrollViewer>
<ScrollViewer Background="Blue">
<StackPanel>
<Label Content="Content as attribute for label."/>
<Label>this is content too</Label>
</StackPanel>
</ScrollViewer>
</StackPanel>
What is Tab control?
A Tab Control is a WPF control with tab items and each tab includes a container for other controls. The WPF TabControl allows you to divide your UI into different areas. Each area can be easily accessed by clicking on the tab header. Tabs are usually placed at the top of the window. Tab controls are commonly used in WPF applications and can also be found in Windows settings like the dialogs for files and folders.
<Grid>
<TabControl>
<TabItem Header="Profile">
<Label Content="Content will show here...you can also add a group of elements" /> </TabItem>
<TabItem Header="Order History" />
<TabItem Header="Privacy" />
</TabControl>
</Grid>
What is WPF Child Window?
A ChildWindow control is a light-weight window that can be used as a child or popup control. The parent window becomes disabled when a child window becomes active and modal. A child window is usually used as a MessageDialogBox to alert the user of some error or as a confirmation. Below is an example of a ChildWindow. In Order to make the child window visible, you need to invoke its Show method.
<wpfx:ChildWindow Name="PopupChildWindow" Caption="A Child Window" IsModal="True" />
What is a Navigation Window?
Navigation Window class inherits Window Class and therefore has all the properties of a Window such as methods, properties and events. However, Navigation window has backward and forward buttons for navigation pages similar to what you would do in a browser.
To create a Navigation Window, use the NavigationWindow container instead of a Window along with the name of the page you want to set as the home page.
What are the different types of Alignments you can use?
In WPF, you can set two different types of alignments: HorizontalAlignment or VerticalAlignment. Horizontal Alignment property takes care of how a child element is a position in relation to its parent horizontally. HorizontalAlignment has four properties: Left, Centre, Right and Stretch. The first three properties are self-explanatory but the stretch takes care to stretch out the child element to fill the parent element’s allocated layout space.
Similarly, Vertical Alignment property does the same thing, but vertically. It has four properties: Top, Bottom, Centre and Stretch.
What are commands in WPF?
A command is an action that can be invoked by using different user actions. For example, editing operations like Copy, Cut and Paste can be applied in several ways because they are commands. For instance, an application might allow a user to copy and paste text either by clicking a button, choosing an item from a menu or context menu or by applying a key combination. By using commands, each type of user action can be applied to the same logic.
Here is a simple example of a command:
<StackPanel>
<Menu>
<MenuItem Command="ApplicationCommands.Copy" /> Copy...</Menu>
</StackPanel>
What is Virtualization in WPF and why do we need it?
What is BAML?
The XAML file can be compiled into a binary XAML file (.baml extension). It is an optimized form of XAML since it uses internal lookups and tokens for commonly used types or members. It is useful for minimizing packaging sies and load time for WPF applications. The BAML file is inserted as a resource into the .NET Framework assembly. At runtime, the framework uses the BAML file from assembly resource, parses it and adds a new WPF visual tree or workflow from it.
How can graphics be represented in WPF?
WPF allows the integration for multimedia, vector graphics, animation, and content composition, making it easy for developers to build interesting user interfaces and content. WPF uses vector graphics to render data formats. The vector graphics include Scalable Vector Graphics (SVG), Windows metafiles and TrueType fonts. The graphics store rendering data and send it as a list of instructions that describe how to build an image using graphics primitives. For instance, TrueType fonts take care of outlining the fonts that describe the calligraphy such as the lines and curves. With vector graphics, any element can be scaled to any size and resolution. This means that the elements/images are scaled are the image fidelity is respected.
Here is an example of a Path scaled to 200%. Note how the path commands instructions remain untouched.
<Path Data="M 0 4 L 4 0 L 8 4 Z"
Fill="{StaticResource linearGradientBackground}"
Stroke="Red" StrokeThickness="3" />
<Path Data="M 0 4 L 4 0 L 8 4 Z"
Fill="{StaticResource linearGradientBackground}"
Stroke="Red" StrokeThickness="3" >
<Path.RenderTransform>
<ScaleTransform ScaleX="2.0" ScaleY="2.0" />
</Path.RenderTransform>
</Path>