Dear Readers, Welcome to WPF Interview Questions and Answers have been designed specially to get you acquainted with the nature of questions you may encounter during your Job interview for the subject of WPF. These WPF Questions are very important for campus placement test and job interviews. As per my experience good interviewers hardly plan to ask any particular questions during your Job interview and these model questions are asked in the online technical test and interview of many IT companies.
Windows Presentation Foundation (WPF) is the presentation subsystem feature of the .NET Framework 3.0,that provide good design and advance controls. Silverlight is the Subset of WPF. Through WPF we can create Windows and WebBrowser Application.
XAML is an extensible markup language based on XML. XAML can be thought of as a declarative script for creating .NET 3.0 UI. It is particularly used in WPF as a user interface markup language to define UI elements, data binding, eventing and other features. It is also used in Windows Workflow Foundation (WF), in which the workflows themselves can be defined in XAML code.
In WPF application it contains many elements. These elements exist in an element tree relationship with each other. A routed event is a type of event that can invoke handlers on multiple listeners in an element tree, rather than just on the object that raised the event.
This is one of the most important features of WPF, separating the XAML from the code to be handled. So designers can independently work on the presentation of the application and developers can actually write the code logic independent of how the presentation is.
The core WPF assemblies are:
WindowsBase.dll:- This is the core types constituting the infrastructure of WPF API.
PresentationCore.dll:- It defines numerous types constituting foundation of WPF GUI layer.
PresentationFoundation.dll:- It defines WPF control types, animation & multimedia support, data binding suport and other WPF services.
Besides these three libraries WPF also uses an unmanaged binary called milcore.dll which acts as a bridge between WPF assemblies and DirectX runtime layer.
WPF Interview Questions & Answers –By Jignesh Patel (Jignesh.tsil@gmail.com) Page 2
XBAP means XAML Browser Application. XBAP allows for WPF applications to be used inside a browser. For this .NET framework is required to be installed on the client system and hosted applications run in a partial trust sandbox environment.
A freezable object is one that has a mechanism that allows you to "Freeze" it. This locks downs all the state and makes the object immutable. This makes the object more performant to use and safer to share between threads.
Path animation in which the object moves along the path specified by the Path geometry. As the animation progresses, it reads the X-axis, Y-axis and angle information from the path geometry and generates the output. These are useful when an object has to be animated along a complex path.
This is the root namespace of several other media related namespaces. It provides different types to work with animations like 3D rendering, text rendering and other multimedia services.
To define a button in WPF using XAML, Syntax is given below-
<Button Name="btnName">btnCaption</Button>
Example:-
<Button Name="btnClick">Click Me</Button>
Here the <Button> element specifies the use of the Button class.
This namespace contains different classes for navigation between windows.
System.Windows.Media.Medi3D namespace is used for working with 3D.
WPF Interview Questions & Answers –By Jignesh Patel (Jignesh.tsil@gmail.com) Page 3
There are two kind of major document supported in WPF Fixed format documents and Flow format document. Fixed format documents look like PDF format. They display content regardless of screen size and resolution. But flow format document adjust depending on screen size and resolution.
These dependency properties belong to one class but can be used in another.
Consider the below code snippet:-
<Rectangle Height="72" Width="131" Canvas.Left="74" Canvas.Top="77" />
Height and Width are regular properties of the Rectangle. But Canvas. Top and Canvas. Left is dependency property as it belongs the canvas class. It is used by the Rectangle to specify its position within Canvas.
The x:Name attribute allows you to uniquely identify an instance of an object defined in XAML. The value of the x:Name attribute can be referenced in the associated C# or VB code.
When your XAML is compiled, you can embed procedural code such as C# or VB. For more information about this, look up the markup extension x:Code.
An attached property is a property that is declared by one control and attached to another. It allows the inclusion of additional information with a control for later use by an external source.
A Panel has a collection of Children that it arranges according to various rules, based on the type of panel. A Decorator, on the other hand, has only one Child to which it applies some additional set of behavior.
AccessText enables you to specify displayed text with an embedded keyboard shortcut used to access the corresponding control. Simply precede the desired letter of the text with an underscore.
WPF Interview Questions & Answers –By Jignesh Patel (Jignesh.tsil@gmail.com) Page 4
Span Bold Italic Underline Hyperlink Run LineBreak InlineUIContainer Figure Floater
Markup extensions are the most common means of declaring a data binding. They are identified by the use of curly brackets ({}).The less common format is XAML.
x:Static is another markup extension that is different from the data binding markup extension. It is used to retrieve data from static value members on classes.
There are three ways to deploy WPF applications : as a simple XAML file an XBAP or a standard executable.
Navigation applications are based on a web browser metaphor. They use pages instead of windows, and they include a forward and back button by default.
A ToolBar can host any type of .NET class.
WPF Interview Questions & Answers –By Jignesh Patel (Jignesh.tsil@gmail.com) Page 5
The easiest way to break up a complex UI is to create separate UserControls for related parts and reference them from the original UI.
To save or load the content of a RichTextBox, use the TextRange class.
There are two types of binding in WPF : Key Binding Mouse Binding
KeyBinding allows you to define gestures for commands that consist of a keystroke possibly combined with one or more modifiers, whereas MouseBinding allows you to define gestures for the mouse that can also be optionally combined with modifiers on the keyboard.
Use RenderTargetBitmap to render WPF visuals to a bitmap.
All elements that are renderable must inherit from Visual.
A repository is a type of class that hides the actual data storage mechanism from the rest of the application.
The common file dialogs that WPF supports include SaveFileDialog, OpenFileDialog, and PrintDialog. WPF does not presently have a common dialog for folder selection, font selection, or print preview.
WPF Interview Questions & Answers –By Jignesh Patel (Jignesh.tsil@gmail.com) Page 6
MediaElement is used to play back a variety of audio and video formats.
There are more than a dozen properties on the base class System.Windows.Shapes.Shape. Fill Stroke StrokeDashArray StrokeDashCap StrokeEndLineCap StrokeLineJoin StrokeMiterLimit StrokeStartLineCap StrokeThickness
There are six different types of brushes SolidColorBrush LinearGradientBrush RadialGradientBrush DrawingBrush VisualBrush ImageBrush
There are four channels of a WPF color objects are : Alpha Red Green Blue
The built-in bitmap effects are : DropShadowBitmapEffect OuterGlowBitmapEffect BlurBitmapEffect EmbossBitmapEffect BevelBitmapEffect
WPF Interview Questions & Answers –By Jignesh Patel (Jignesh.tsil@gmail.com) Page 7
The two transforms that are present on FrameworkElement are RenderTransform and LayoutTransform.
There are three types of sibling libraries of WPF are : WCF WF CardSpace
Windows Communication Foundation is focused on messaging. This API greatly simplifies all sorts of networking and communication tasks. It covers everything from web services to remoting to P2P and more. A powerful library for building workflow enabled applications. It utilizes a markup language for declaring workflows in an application,and thus prevents workflow from becoming hard-coded. It also makes it very easy for developers to create custom workflow tasks.
WPF is currently available on Windows XP and Windows Vista.
There are three different binding modes : one–way two–way one–way–to–so
The XAML file contains the XAML markup, whereas the code-behind file is associated with a XAML file and contains code (such as C# or VB).
App.xaml and Window1.xaml, along with their associated code-behind files. The former represents the application as a whole, whereas the latter represents the primary window of the application.
WPF Interview Questions & Answers –By Jignesh Patel (Jignesh.tsil@gmail.com) Page 8
The System.Windows.Markup namespace provides some helper classes for XAML code.
The "System.Windows.Interop" namespace provides classes for integration of WPF with Win32.
In One-way-to-Source binding when the target property changes, the source object gets updated.
Yes, It's is possible for a control to define a handler for an event, that the control can't itself raise. These incidents are called attached events. For example, a button controls in a grid. The button class defines a click event, but the grid class does not. However, you can still define a handler for buttons in the grid by attaching the Click events of the button control.
The User Settings are Read/Write, they can be read or write even at runtime and can be saved. The Application Settings are read-only, they can only be written at design time.
It is the technique through which one style aquires the features of another style It is implemented through BasedOn property of the Style class. example:
<Window x:Class="WpfApplication14jan.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Window.Resources>
<Style x:Key="One" TargetType="{x:Type Button}"> <Setter Property="Foreground" Value="Green"/> </Style>
<!-- This is how the style inheritance is implemented-->
<Style x:Key="Two" BasedOn="{StaticResource One}" TargetType="{x:Type Button}"> <Setter Property="Background" Value="Yellow"/> </Style> </Window.Resources> <Button Height="100" Width="100" Style="{StaticResource Two}" Content="Welcome"> </Button> </Window>
WPF Interview Questions & Answers –By Jignesh Patel (Jignesh.tsil@gmail.com) Page 9
Consider this XAML declaration
<Window x:Class="WpfApplication14jan.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> </Window>
The attribute xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" is responsible for the mapping. Without this, no XAML user interface can be created or code executed.
MediaPlayer has no visual interface and not suitable to display videos. It cannot be placed on the XAML designer. It provides Media PlayBack for drawings. We have to use VideoDrawing or DrawingContext classes for that. example:
MediaPlayer player = new MediaPlayer(); player.Open(new Uri("c:\\intro.wmv", UriKind.Relative)); VideoDrawing aVideoDrawing = new VideoDrawing(); aVideoDrawing.Rect = new Rect(0, 0, 100, 100); aVideoDrawing.Player = player; player.Play(); MediaElement has got visual interface and can easily display videos using its built in properties. It is designed for XAML use and can be placed on the XAML designer.
Data Templates: Data Template visual representation of data in control with style. like List box. Control Templates: Control Template suppliers a visual representation of a UI Control like Button or List View. Items Panel Templates:Item Panel Templates uses when we want to show data in Hierarchical way like child object use under parent object.
WPF Interview Questions & Answers –By Jignesh Patel (Jignesh.tsil@gmail.com) Page 10
The WPF Unit is measured in DPI. First we need to understand about DPI and PX (i.e. Device Independent Pixels & Physical Pixels) 1 DPI = 1/96 inch 1 PX = 1/DPI - Depends on screen type The default system setting is 96 DPI Note: If the DPI increases, the number of physical pixels which compose one device independent pixel also increases. Hence, objects that have their sizes specified in device independent pixels get larger as the system DPI increases
* System.Threading.DispatcherObject class represents on object associated with a "Dispatcher". * System.Windows.DependencyObject class is the base class for classes that support dependency properties. * System.Windows.Media.Visual class is the base class for objects that can be rendered to a WPF window or page. * System.Windows.UIElement class defines core subsystems like Layout, Input, Focus and Events(LIFE). * System.Windows.FrameworkElement introduces data binding and data templates, styles and animation. * System.Windows.Controls.Control class adds a feature called templating. This is the base class for all the controls that the user interacts with. * System.Windows.Controls.ContentControl can hold a single nested element
* This interface contains a single event called "PropertyChanged" of the delegate type "PropertyChangedEventHandler". * To notify the WPF/Silverlight framework whenever the value of a property changes in an object, fire the event in the "set" accessor of the property
* This interface is similar to INotifyPropertyChanged, which is to be implemented to notify the WPF/Silverlight framework whenever any changes occur in a collection, like adding an object or deleting an object. * "ObservableCollection" is a built-in class which implements the INotifyCollectionChanged interface.
WPF Interview Questions & Answers –By Jignesh Patel (Jignesh.tsil@gmail.com) Page 11
* Logical tree describes the relations between elements of the user interface. * Every aspect of WPF (properties, events, resources, and so on) has behavior tied to the logical tree. * Logical tree is responsible for: 1) Inherit Dependency Property values 2) Resolving Dynamic Resources references 3) Looking up element names for bindings 4) Forwarding Routed Events * System.Windows.LogicalTreeHelper class is used to traverse the logical tree.
* Visual tree is an expansion of a logical tree, in which nodes are broken down into their visual components. * Visual tree contails all logical elements including all visual elements. * The elements that appear in a visual tree derive from 'System.Windows.Media.Visual' and 'System.Windows.Media.Visual3D'. * Visual tree is responsible for: 1) Rendering visual elements 2) Propagate element opacity 3) Propagate layout and render transforms 4) Propagate the 'IsEnabled' property 5) Do hit-testing NOTE: * Visual tree is dependent on Windows theme. * Visual tree is empty until the window undergoes layout at least once. So it must be navigated in 'OnContentRendered' event handler. * System.Windows.VisualTreeHelper class is used to traverse the logical tree.
1) Binary Resources Binary resources could be logo/image files, AV files etc. 2) Logical Resources are of tow types: Static and Dynamic Resources * StaticResource finds the key defined within the ResourceDictionary under its scope during the Loading of the application. * Hence the Compiler will throw error during compilation if not found in resources. -- * DynamicResource Markup Extension defers the resource assignment to the actual runtime of the application. * So the expression remains unevaluated until the object being created.
WPF Interview Questions & Answers –By Jignesh Patel (Jignesh.tsil@gmail.com) Page 12
* Binary resources could be logo/image files, AV files etc. * Resource files which are added to project, can have the “Build Action” defined on it from the file properties windows: - Resource : Embeds resource into the assembly (or culture specific satellite assembly) - Content : this leaves resource as loose file and upon compilation this resource information is not embedded to assembly. Instead, it adds custom attribute to the assembly (AssemblyAssociatedContentFile) which records the existence and relative location of file.
* StaticResource finds the key defined within the ResourceDictionary under its scope during the Loading of the application. * Hence the Compiler will throw error during compilation if not found in resources.
* DynamicResource Markup Extension defers the resource assignment to the actual runtime of the application. * So the expression remains unevaluated until the object being created.
* StaticResource requires less CPU during runtime, so it is faster. * StaticResource are created when the application loads. So making everything as StaticResource means slowing down the Application Load process. * When the resources are unknown during compilation, you can use DynamicResource. * DynamicResource are used when user interaction changes the look and feel of an object.
* The WPF styling and templating model enables you to specify Triggers within your Style. * Essentially, Triggers are objects that enable you to apply changes when certain conditions (such as when a certain property value becomes true, or when an event occurs) are satisfied. * Types of triggers: 1) Property triggers get active when a property gets a specified value. 2) Data triggers get active when a specified event is fired. 3) Event triggers get active when a binding expression reaches a specified value.
WPF Interview Questions & Answers –By Jignesh Patel (Jignesh.tsil@gmail.com) Page 13
* A Template is used to change how a control looks. * Types of templates: 1) Control template: How a control is rendered and behaves by specifying the visual structure and behavioral aspects. 2) Data template: To specify the visualization of data objects. 3) Hierarchical data template: Used over hierarchical structure like TreeView and Menu.
* Application is a class that represents a WPF application running as a standalone client application in Windows. * Each running application contains at most a single instance of Application. * The Application object is defined in the App.xaml file and is responsible for: - Managing application lifetime (e.g. responding to startup/shutdown events) - Window, property and resource management - Command-line processing - Navigation
The main events fired from Application include: * Startup - Application is starting up. * Exit – Fired when an application is shutting down. * Activated – Fired when an application gets focus, i.e. becomes the foreground application * Deactivated – Fired when application loses focus, i.e. is no longer the foreground application * DispatcherUnhandledException – Fired when an exception is thrown, but not yet handled. You can choose to handle the exception or not * SessionEnding – Fired when Windows is being shut down–due to either logoff or Windows shutdown. You can cancel the shutdown sequence. * You can add custom code for any of these events by just overriding the OnEventName method in your Application-derived class, e.g. OnStartup.
* At application startup, the Window events that are fired (in order) for the main window are: 1) Initialized - Main window is being created 2) IsVisibleChanged - IsVisible property set to true 3) SizeChanged - Size property set to size of window 4) LayoutUpdated - Window layout changes 5) SourceInitialized - Window is attached to Win32 window handle 6) Activated - Window becomes foreground window 7) PreviewGotKeyboardFocus - Window getting focus
WPF Interview Questions & Answers –By Jignesh Patel (Jignesh.tsil@gmail.com) Page 14
8) IsKeyboardFocusWithinChanged - IsKeyboardFocusWithin property set to true 9) IsKeyboardFocusedChanged - IsKeyboardFocused property set to true 10) GotKeyboardFocus - Window now has keyboard focus 11) LayoutUpdated - Window layout changes 12) Loaded - Window is now laid out, fully rendered 13) ContentRendered - All window content has been rendered
1) Closing - Window is going to close 2) IsVisibleChanged - IsVisible property set to false 3) Deactivated - Window becomes background window 4) IsKeyboardFocusWithinChanged - IsKeyboardFocusWithin property set to false 5) IsKeyboardFocusedChanged - IsKeyboardFocused property set to false 6) LostKeyboardFocus - Window no longer has keyboard focus 7) Closed - Window is closing
1) Import the following namespaces: using System.Windows.Forms; using System.Windows.Forms.Integration; 2) Create the windows forms control and set its properties and event handlers. 3) Add the control to the 'Child' property of 'WindowsFormsHost' object. 4) Add the host object to the 'Children' collection of the panel.
1) Add reference to the following: a) Presentation Core b) Presentation Framework c) WindowsBase d) WindowsFormsIntegration e) System.Xaml 2) Also add reference to the WPF control DLL. 3) Use the 'ElementHost' control in 'WPF Interoperability' tab in Toolbox to host WPF controls.
WPF Interview Questions & Answers –By Jignesh Patel (Jignesh.tsil@gmail.com) Page 15
Elements of a WPF user interface are hierarchically related. This relation is called the LogicalTree. The template of one element consists of multiple visual elements. This tree is called the VisualTree. WPF differs between those two trees, because for some problems you only need the logical elements and for other problems you want all elements.
<Window>
<Grid>
<Label Content="Label" />
<Button Content="Button" />
</Grid>
</Window>
A WPF control consists of multiple, more primitive controls. A button - for example - consists of a border, a rectangle and a content presenter. These controls are visual children of the button. When WPF renders the button, the element itself has no appearance, but it iterates through the visual tree and renders the visual children of it. This hierarchical relation can also be used to do hit-testing, layout etc. But sometimes you are not interested in the borders and rectangles of a controls' template. Particularly because the template can be replaced, and so you should not relate on the visual tree structure! Because of that you want a more robust tree that only contains the "real" controls - and not all the template parts. And that is the eligibility for the logical tree.