WPF interview questions

By | September 8, 2013

Windows Presentation Foundation (WPF) Interview questions

What is WPF?

Windows Presentation Foundation (WPF) provides developers with a unified programming model for building rich Windows Forms applications that incorporate user interface (UI), media, and documents. WPF enables software developers to deliver a new level of “user experience” (UX) by providing a declarative-based language (XAML) for specifying vector-based graphics that can scale and take advantage of hardware acceleration.All display in WPF is done through the DirectX engine, allowing for efficient hardware and software rendering

Explain Dependency property
  1. It is a special property system supported by WPF. The purpose of DP is to provide a way to compute the value of a property based on the value of other inputs. 
  2. DependencyObject defines the base class that can register and own a dependency property. DP provides functionality that supports features of WPF like 
    1. 1) Resources
    2. 2) Data Binding
    3. 3) Styles, templates, change notification, animations, property value inheritance 
  3. The value of a dependency property is resolved dynamically when calling the GetValue() method that is inherited from DependencyObject.
  4. The dependency property is a public static read-only field that must be registered first. After it has been registered, this static property is used to get and set the value in the internal storage system.

What are Attached Properties?
  1. They are a special type of dependency property. With an attached property, the property is defined on a class that isn’t the same class for which it’s being used.
  2. This is usually used for layout. They are basically meant for the container elements.
  3. WPF elements are built on the principle of composition and component reuse. It is often the case that some containing element (like a Grid layout element) needs additional data on child elements to control its behavior (like the Row/Column information).
  4. Attached properties allow child elements to define values for a parent element’s properties.  They only make sense in the context of a hierarchical element tree.

WPF styles:
  1. It is a convenient way to apply a set of property values to more than one element to provide a consistent visual appearance.You can use a style on any element that derives from FrameworkElement or FrameworkContentElement. 
  2. Styles are defined as a resource in the Resources section in a xaml file.  Style resources obey scoping rules and are applicable by type.

WPF Data Templates & HierarchicalDataTemplate
  1. Data Template is about the structure and presentation of data. 
  2. They are reusable. 
  3. ListView,ListBox, drop down list controls employ data templates.  
  4. HierarchicalDataTemplate is useful if you’re displaying collections that contains other collections like Menu or Treeview. 
  5. DataTemplateSelector allows you to choose a DataTemplate to use based on custom logic.

WPF Control Templates:
  1. Controls in WPF have a ControlTemplate that contains the visual tree of that control. 
  2. ControlTemplate – Defines the entire layout of a control (rather than just what is substituted in the ContentPresenter).  It is defined to exist within a Template property for a Control.
  3. When you are defining a new template for the Button control, if you do not specify a ContentPresenter somewhere in your control template, the Button will not behave as intended i.e. no matter what is specified for the Content property , it will not be displayed within your newly templated Button.
  4. Example of Template hierarchy for ItemsControl and buttonControl
    •            ItemsControl -> ItemsPanelTemplate -> ItemTemplate -> DataTemplate
    •            ItemsControl -> ControlTemplate -> ItemPresenter
    •            ButtonControl ->ControlTemplate ->ContentPresenter
WPF Triggers:
  1. A trigger sets properties or starts actions when a property value changes or when an event is raised. Style, controlTemplate and dataTemplate all have a Triggers property that can contain a set of triggers.
  2. Types of triggers
    • PropertyTriggers – A property reaches some value
    • EventTriggers – A particular event has occurred
    • DataTriggers – A particular property of the DataContext has reached some value
    • MultiTriggers – Several properties have met some condition

Difference between VisualTree & LogicalTree

  1. The logical tree is the externally visible element hierarchy that a consumer of the control gets to program against.
  2. Visual tree for a control is what contributes to complete look & feel of the control. Ex: border, contentPresenter, grid, rectangle, text block in a button control.
  3. The visual tree represents all of the elements in your UI which render. Walking up and down the visual tree can be a simple matter of just using VisualTreeHelper and some simple recursive methods.

WPF DataBinding: 
  1. With proper binding expressions and change notifications, when data changes it’s value the element that are bound to the data reflect changes automatically. 
  2. Each binding has four components: a binding target object, a target property, binding source and a path to the value in the binding source. For example, if you want to bind the content of a TextBox to the Nameproperty of an Employee object, your target object is the TextBox, the target property is the Text property, the value to use is Name, and the source object is the Employee object.
  3. The data flow of a binding can go from the binding target to the binding source and vice versa. One way, two way and oneWayToSource are different modes of data flow.
  4. OneWay binding applies changes from source property to target property, but changes to the target property are not propagated back to the source property.
  5. TwoWay binding causes changes to either the source property or target property to automatically update the other.
  6. OneWayToSource is the reverse of OneWaybinding; it updates the source property when the target property changes.
  7. To detect source changes, the source must implement property change notification such as INotifyPropertyChanged. 
  8. The UpdateSourceTrigger property of binding determines what triggers the update of the source.

What is DataContext?
  1. Every WPF control derived from FrameworkElement has a DataContext property. This property is meant to be set to the data object it visualizes. The DataContext property inherits it’s value to child elements. 

  1. If you want to bind two properties of different types together, you need to use a  ValueConverter. (Ex: Color object to solidColorBrush to apply for background property). or (binding  a bool member to the visibility property)
  2. A ValueConverter converts the value from a source type to a target type and back. You can write your own converter by implementing IValueConverter interface

  1. A MultiBinding works just a regular Binding except it must have a Converter specified and can have multiple pieces of data bound to it, so when any of these change it fires a re-evaluation of the lot.

  1. Most objects in WPF derive from DispatcherObject, which provides the basic constructs for dealing with concurrency and threading. All updates to UI thread are dispatched from background threads using dispatcherObject.

WPF Routed Event Model:
  1. All events in WPF have a notion of routing through the element tree. Events are said to “bubble” if they traverse from a target up the tree to the root, and are said to “tunnel” if that start at the root and traverse down to a target.
  2. Routed events can invoke handlers on other objects in the element tree aside from just the originating object that raised the event.  This means that events for a chain of elements can be triggered in sequence allow them to tunnel down and bubble up the visual & logical trees from element to element
  3. There are 3 types of routing strategies
    • Tunnelling travels towards to the leaves of the visual/logical tree
    • Bubbling travels towards the root of the visual/logical tree
    • Direct can only be handled by the object that raised the event

Explain FrameworkElement?
  1. FrameworkElement provides a framework of common APIs for objects that participate in application layout. FrameworkElement also defines APIs related to data binding, object tree
  2. The two most critical things that FrameworkElement introduces are data binding and styles.

What is Content Control and explain difference between ContentPresenter and ItemsPresenter?
  1. ContentControl – A control that allows developers to define UIElements that can be displayed within the control
  2. ContentPresenter – A stub in the ControlTemplate for where the content from the Content property of a ContentControl should be inserted
  3. ItemsControl – Control that displays a collection of items
  4. ItemsPresenter – An ItemsControl.Template can contain a ControlTemplate.  The 
  5. ItemsPresenter is the stub for where the items should be rendered in the ControlTemplate

  1. They provide a method that allows events for multiple elements share the same command
  2. The command is defined in a CommandBindings element.  Any of the child elements of the main container can reference the commands

ContentControl and ItemsControl:
  1. ContentControl is intended to display a single piece of content.
  2. ItemsControl, as suggested by the name, is meant to display multiple items within it. 

MVVM architecture:
  1. MVVM is a architectural pattern custom tailored for WPF and Silverlight. 
  2. Views interact with the view model by bindings, commands, events. 
  3. ViewModel is a specialized form of controller. 
  4. The view model of MVVM is a value converter meaning that the view model is responsible for exposing the data objects from the domain model in such a way that those objects are easily managed and consumed
  5. View model: the view model is a “model of the view” meaning it is an abstraction of the view that also serves in mediating between the view and the model which is the target of the view data bindings. 
  6. The view model exposes public properties, commands, and abstractions.

  • Prism is the Microsoft Patterns and Practices Team official guidance for building “composite applications” in WPF and Silverlight.
  • Prism helps you to design and build applications using loosely coupled components that can evolve independently but which can be easily and seamlessly integrated into the overall application. Such applications are known as often referred to as composite applications.
  • Modules contribute the views from which the main composite view (otherwise known as the shell) is created. Modules never directly reference each other, nor do they directly reference the shell. Instead, they utilize services to communicate with one another and with the shell in order to respond to user actions.
  • The CAL provides the services and plumbing for building composite apps. It uses a composition model that allows each of its services to be used piecemeal or together as part of a CAL-designed app. Each service is also easily replaceable without recompilation of the CAL. For example, the CAL ships with an extension that uses the Unity Application Block for dependency injection
  • Its intended to provide guidance on the best practices for building large scale applications which are flexible in terms of development and maintainability.
  • This includes guidance on dependency injection (via Unity or MEF), layout (including using MVVM), composite event handling, etc.
  • In a WPF-Prism-Unity application, the Shell divides its UI up into regions. A region is any one of the XAML controls that implements the IRegion interface and is tagged with the RegionName attribute
  • With the regions defined, the Shell can now use the Prism-provided RegionManager to retrieve views (WPF UserControls defined in a Module) from the Unity container and load them into the UI.
  • Provides guidance and a re-usable library to help you develop flexible, easy to maintain WPF and Silverlight composite applications
  • Helps you to understand, implement and use key design patterns, such as MVVM and Dependency Injection

Differences between WPF and Silverlight:
  1. Dynamic resource references are not supported in Silverlight; therefore, only static resource references are available.
  2. Silverlight does not currently support MergedDictionaries.
  3. Silverlight does not support triggers in Styles, ControlTemplates, or DataTemplates (the Triggers collection does not exist on these elements). However, similar behavior can be achieved by using the Silverlight Visual State Manager (VSM) to define interactive control templates. Using VSM, the visual behavior of a control, including any animations and transitions, are defined in the control template.
  4. Silverlight does not support the RelativeSource property, which is useful when the binding is specified in a ControlTemplate or a Style.
  5. In Silverlight, there is no OneWayToSource data flow mode.
  6. In Silverlight, there is no UpdateSourceTrigger property. All updates to the source in the two-way binding mode occur immediately, except in the case of TextBox, in which case changes are propagated to the source when the focus is lost.
  7. In Silverlight, there is no ReadOnlyObservableCollection; however, ObservableCollection is supported. ReadOnlyObservableCollection is a read-only wrapper around the ObservableCollection. The ObservableCollection represents a dynamic data collection that provides notifications when items get added, removed, or when the whole collection gets refreshed.
  8. In Silverlight, there is no DataTemplateSelector class. In WPF, this class provides a way to choose a DataTemplate based on the data object and the data-bound element.
  9. Routed commands are not available in Silverlight.

Page navigation in WPF:
  1. Windows Presentation Foundation (WPF) supports browser-style navigation that can be used in two types of applications: standalone applications and XAML browser applications (XBAPs). 
  2. To package content for navigation, WPF provides the Pageclass. You can navigate from one Page to another declaratively, by using a Hyperlink, or programmatically, by using the NavigationService. 
  3. WPF uses the journal to remember pages that have been navigated from and to navigate back to them.
  4. Page , Hyperlink, NavigationService, and the journal form the core of the navigation support offered by WPF.

WPF Animation:
  1. In WPF, you animate objects by applying animation to their individual properties. For example, to make a framework element grow, you animate its Width and Height properties. To make an object fade from view, you animate its Opacity property. • It must be a dependency property.
  2. DoubleAnimation creates a transition between two double values. To specify its starting value, you set its From property. To specify its ending value, you set its To property.
  3. The Storyboard has to know where to apply the animation. Use the Storyboard.TargetName attached property to specify the object to animate.
  4. The easiest way to apply and start a Storyboard in XAML is to use an event trigger. This section shows how to associate the Storyboard with a trigger in XAML.
  5. The Visual State Manager allows you to create “states” of objects and then move to those states. Moving to those states can be done through code(just one line of code), or by using behaviors.