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
- 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.
- DependencyObject defines the base class that can register and own a dependency property. DP provides functionality that supports features of WPF like
- 1) Resources
- 2) Data Binding
- 3) Styles, templates, change notification, animations, property value inheritance
- The value of a dependency property is resolved dynamically when calling the GetValue() method that is inherited from DependencyObject.
- 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?
- 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.
- This is usually used for layout. They are basically meant for the container elements.
- 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).
- 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.
- 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.
- 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
- Data Template is about the structure and presentation of data.
- They are reusable.
- ListView,ListBox, drop down list controls employ data templates.
- HierarchicalDataTemplate is useful if you’re displaying collections that contains other collections like Menu or Treeview.
- DataTemplateSelector allows you to choose a DataTemplate to use based on custom logic.
WPF Control Templates:
- Controls in WPF have a ControlTemplate that contains the visual tree of that control.
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.
- 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.
- Example of Template hierarchy for ItemsControl and buttonControl
- ItemsControl -> ItemsPanelTemplate -> ItemTemplate -> DataTemplate
- ItemsControl -> ControlTemplate -> ItemPresenter
- ButtonControl ->ControlTemplate ->ContentPresenter
- 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.
- 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
- The logical tree is the externally visible element hierarchy that a consumer of the control gets to program against.
- 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.
- 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.
- With proper binding expressions and change notifications, when data changes it’s value the element that are bound to the data reflect changes automatically.
- 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.
- 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.
- OneWay binding applies changes from source property to target property, but changes to the target property are not propagated back to the source property.
- TwoWay binding causes changes to either the source property or target property to automatically update the other.
- OneWayToSource is the reverse of OneWaybinding; it updates the source property when the target property changes.
- To detect source changes, the source must implement property change notification such as INotifyPropertyChanged.
- The UpdateSourceTrigger property of binding determines what triggers the update of the source.
What is DataContext?
- 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.
- 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)
- 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
- 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.
- 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:
- 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.
- 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
- 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
- FrameworkElement provides a framework of common APIs for objects that participate in application layout. FrameworkElement also defines APIs related to data binding, object tree
- The two most critical things that FrameworkElement introduces are data binding and styles.
What is Content Control and explain difference between ContentPresenter and ItemsPresenter?
- ContentControl – A control that allows developers to define UIElements that can be displayed within the control
- ContentPresenter – A stub in the ControlTemplate for where the content from the Content property of a ContentControl should be inserted
- ItemsControl – Control that displays a collection of items
- ItemsPresenter – An ItemsControl.Template can contain a ControlTemplate. The
- ItemsPresenter is the stub for where the items should be rendered in the ControlTemplate
- They provide a method that allows events for multiple elements share the same command
- The command is defined in a CommandBindings element. Any of the child elements of the main container can reference the commands
ContentControl and ItemsControl:
- ContentControl is intended to display a single piece of content.
- ItemsControl, as suggested by the name, is meant to display multiple items within it.
- MVVM is a architectural pattern custom tailored for WPF and Silverlight.
- Views interact with the view model by bindings, commands, events.
- ViewModel is a specialized form of controller.
- 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
- 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.
- 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:
- Dynamic resource references are not supported in Silverlight; therefore, only static resource references are available.
- Silverlight does not currently support MergedDictionaries.
- 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.
- Silverlight does not support the RelativeSource property, which is useful when the binding is specified in a ControlTemplate or a Style.
- In Silverlight, there is no OneWayToSource data flow mode.
- 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.
- 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.
- 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.
- Routed commands are not available in Silverlight.
Page navigation in WPF:
- Windows Presentation Foundation (WPF) supports browser-style navigation that can be used in two types of applications: standalone applications and XAML browser applications (XBAPs).
- 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.
- WPF uses the journal to remember pages that have been navigated from and to navigate back to them.
- Page , Hyperlink, NavigationService, and the journal form the core of the navigation support offered by WPF.
- 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.
- 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.
- The Storyboard has to know where to apply the animation. Use the Storyboard.TargetName attached property to specify the object to animate.
- 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.
- 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.