| Array, ArrayList and List :👈 | 👉:WPF QA 121-130 |
WPF (Windows Presentation Foundation) Question Answers - 111 to 120 |
WPF Interview Questions and Answers
Table of Contents
- Style and Template
- Data Binding
- Visual, UIElement, and FrameworkElement
- INotifyPropertyChanged
- ResourceDictionary
- UserControls vs Custom Controls
- Converters
- Routed Events vs Commands
- Bubbling vs Tunneling Events
- Container Controls
111. What Is a Style and a Template?
Style
A Style is a collection of property settings that can be reused across multiple controls. It helps maintain a consistent appearance and reduces duplicate XAML.
<Window.Resources>
<Style x:Key="PrimaryButtonStyle"
TargetType="Button">
<Setter Property="Background"
Value="SteelBlue"/>
<Setter Property="Foreground"
Value="White"/>
<Setter Property="FontSize"
Value="16"/>
<Setter Property="Padding"
Value="10,5"/>
</Style>
</Window.Resources>
<Button Content="Save"
Style="{StaticResource PrimaryButtonStyle}"/>
The style defines the background, foreground, font size, and padding of the button.
Template
A Template defines how a control or data item is visually represented.
- ControlTemplate: Defines the visual structure of a control.
- DataTemplate: Defines how a data object is displayed.
ControlTemplate Example
<ControlTemplate x:Key="SimpleButtonTemplate"
TargetType="Button">
<Border Background="{TemplateBinding Background}"
CornerRadius="8"
Padding="10">
<ContentPresenter
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Border>
</ControlTemplate>
This template uses a rounded Border and a ContentPresenter to display the button content.
| Style | Template |
|---|---|
| Sets reusable property values. | Defines visual structure or data presentation. |
| Commonly changes colors, fonts, margins, and padding. | Can replace the visual structure of a control. |
| Uses Setter elements. | Uses ControlTemplate or DataTemplate. |
Interview takeaway: A Style changes property values, while a ControlTemplate changes a control's visual structure and a DataTemplate changes how data is displayed.
112. What Is Data Binding and How Does It Work?
Data Binding connects a source property to a target property, allowing data to flow between an object and a UI element.
It is commonly used with the MVVM (Model-View-ViewModel) pattern.
How It Works
- Define a source object, such as a ViewModel.
- Set the DataContext to that object.
- Bind a UI property to a source property using XAML.
- WPF evaluates the binding and transfers values according to the binding mode.
- Change notifications allow the UI to refresh when the source changes.
XAML Example
<StackPanel Margin="20">
<TextBox Text="{Binding UserName,
UpdateSourceTrigger=PropertyChanged}"
Width="200"/>
<TextBlock Text="{Binding UserName}"
Margin="0,10,0,0"/>
</StackPanel>
C# Example
public class UserViewModel
{
public string UserName { get; set; } = "Alex";
}
Window Code-Behind
public MainWindow()
{
InitializeComponent();
DataContext = new UserViewModel();
}
Both controls bind to the UserName property. The TextBox can update the source property as the user types. However, for the TextBlock to automatically reflect subsequent source changes, the source must provide suitable change notifications, such as INotifyPropertyChanged.
Binding Modes
| Mode | Description |
|---|---|
| OneWay | Source changes update the target. |
| TwoWay | Changes flow in both directions. |
| OneTime | Sets the target value once when the binding is established. |
| OneWayToSource | Target changes update the source. |
| Default | Uses the target dependency property's default binding mode. |
Interview takeaway: Data binding separates UI presentation from application data and reduces manual UI update logic.
113. Explain Visual, UIElement, and FrameworkElement
These classes form important layers in WPF's UI architecture.
Visual
System.Windows.Media.Visual is the base class responsible for visual rendering infrastructure.
- Rendering and drawing information.
- Visual transformations.
- Clipping.
- Visual-tree relationships.
UIElement
System.Windows.UIElement derives from Visual and adds fundamental UI behavior.
- Mouse and keyboard input handling.
- Routed events.
- Layout through Measure and Arrange.
- Hit testing and focus-related behavior.
FrameworkElement
System.Windows.FrameworkElement derives from UIElement and adds higher-level framework features.
- Data binding support.
- Styles and resource lookup.
- DataContext inheritance.
- Name and layout properties.
- Alignment, margins, and dimensions.
Simplified Class Hierarchy
Visual
└── UIElement
└── FrameworkElement
└── Control
├── Button
├── TextBox
└── ListBox
This is a simplified hierarchy; not every WPF element derives from FrameworkElement.
| Class | Main Responsibility |
|---|---|
| Visual | Visual rendering infrastructure. |
| UIElement | Input, routed events, and layout. |
| FrameworkElement | Framework-level layout, resources, styles, and binding. |
| Control | Reusable interactive controls and templating. |
Interview takeaway: Visual provides rendering infrastructure, UIElement adds interaction and layout, and FrameworkElement adds higher-level framework services.
114. Explain the Importance of INotifyPropertyChanged
INotifyPropertyChanged is an interface in the System.ComponentModel namespace. It notifies data-binding clients when a property's value changes.
Why Is It Needed?
Suppose a TextBlock displays a ViewModel property. If the property changes in C#, WPF needs a way to know that the displayed value must be refreshed.
Implementing INotifyPropertyChanged allows the source object to raise a PropertyChanged event when a property changes.
C# Example
using System.ComponentModel;
using System.Runtime.CompilerServices;
public class UserViewModel : INotifyPropertyChanged
{
private string _userName = "Alex";
public string UserName
{
get => _userName;
set
{
if (_userName != value)
{
_userName = value;
OnPropertyChanged();
}
}
}
public event PropertyChangedEventHandler?
PropertyChanged;
protected void OnPropertyChanged(
[CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(
this,
new PropertyChangedEventArgs(propertyName));
}
}
XAML Example
<TextBlock Text="{Binding UserName}"/>
When UserName changes, OnPropertyChanged raises the event and WPF refreshes the bound TextBlock.
Benefits
- Keeps the UI synchronized with source data.
- Supports the MVVM architecture.
- Reduces manual UI refresh logic.
- Makes ViewModels easier to test independently.
Important: INotifyPropertyChanged does not automatically make properties thread-safe or notify WPF about arbitrary changes inside a collection. ObservableCollection is commonly used to notify the UI about collection changes.
115. What Is ResourceDictionary?
A ResourceDictionary is a collection of reusable WPF resources, such as styles, brushes, templates, converters, and other objects.
It centralizes UI definitions and makes them reusable across windows and controls.
Example: App.xaml
<Application.Resources>
<ResourceDictionary>
<SolidColorBrush x:Key="PrimaryBrush"
Color="SteelBlue"/>
<Style x:Key="HeadingStyle"
TargetType="TextBlock">
<Setter Property="Foreground"
Value="{StaticResource PrimaryBrush}"/>
<Setter Property="FontSize"
Value="24"/>
<Setter Property="FontWeight"
Value="Bold"/>
</Style>
</ResourceDictionary>
</Application.Resources>
Using the Resource
<TextBlock Text="Dashboard"
Style="{StaticResource HeadingStyle}"/>
Merging External Dictionaries
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary
Source="Resources/Styles.xaml"/>
<ResourceDictionary
Source="Resources/Colors.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
Common Resource Types
| Resource | Purpose |
|---|---|
| SolidColorBrush | Reusable colors. |
| Style | Reusable property settings. |
| ControlTemplate | Reusable control appearance. |
| DataTemplate | Reusable data presentation. |
| Converter | Converts binding values. |
StaticResource is generally used for resources resolved during XAML loading. DynamicResource supports runtime resource reevaluation, which is useful for themes and replaceable resources.
Interview takeaway: ResourceDictionary improves reuse, maintainability, and consistency across the application.
116. UserControls vs Custom Controls
UserControl
A UserControl combines existing WPF controls into a reusable component. Its visual structure is normally defined in XAML.
<UserControl x:Class="MyApp.UserControls.UserInfo"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel>
<TextBlock Text="User Information"
FontWeight="Bold"/>
<TextBox Width="200"/>
</StackPanel>
</UserControl>
It can be reused in a Window:
<local:UserInfo/>
Custom Control
A Custom Control is generally a class derived from Control or another suitable control base class. It is useful when you need a reusable component whose appearance can be customized through templates.
The appearance is commonly defined in a theme dictionary, such as Themes/Generic.xaml.
C# Example
using System.Windows;
using System.Windows.Controls;
public class RatingControl : Control
{
static RatingControl()
{
DefaultStyleKeyProperty.OverrideMetadata(
typeof(RatingControl),
new FrameworkPropertyMetadata(
typeof(RatingControl)));
}
public static readonly DependencyProperty RatingProperty =
DependencyProperty.Register(
nameof(Rating),
typeof(int),
typeof(RatingControl),
new PropertyMetadata(0));
public int Rating
{
get => (int)GetValue(RatingProperty);
set => SetValue(RatingProperty, value);
}
}
Template Example
<Style TargetType="{x:Type local:RatingControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:RatingControl}">
<TextBlock Text="{Binding Rating,
RelativeSource={RelativeSource TemplatedParent}}"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
| UserControl | Custom Control |
|---|---|
| Usually composed in XAML. | Usually starts with a custom control class. |
| Best for fixed combinations of existing controls. | Best for reusable, themeable controls. |
| Visual structure is generally defined in its XAML file. | Visual structure can be replaced using ControlTemplate. |
| Requires less setup for composite UI. | Provides more flexibility for styling and templating. |
Interview takeaway: Use UserControl for composing existing UI elements. Use a Custom Control when you need a reusable control with a customizable template.
117. What Are Converters and How Do They Work?
A Value Converter transforms a value from one type or representation to another during data binding.
WPF converters commonly implement IValueConverter or IMultiValueConverter.
Common Uses
- Converting a Boolean into Visibility.
- Converting a numeric value into formatted text.
- Converting an enum into a display label.
- Transforming values for presentation without adding UI logic to the ViewModel.
Example: Boolean to Visibility
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
public class BoolToVisibilityConverter : IValueConverter
{
public object Convert(
object value,
Type targetType,
object parameter,
CultureInfo culture)
{
return value is true
? Visibility.Visible
: Visibility.Collapsed;
}
public object ConvertBack(
object value,
Type targetType,
object parameter,
CultureInfo culture)
{
return value is Visibility.Visible;
}
}
XAML Resource Declaration
<Window.Resources>
<local:BoolToVisibilityConverter
x:Key="BoolToVisibilityConverter"/>
</Window.Resources>
Using the Converter
<TextBlock Text="Operation completed">
<TextBlock.Visibility>
<Binding Path="IsCompleted"
Converter="{StaticResource BoolToVisibilityConverter}"/>
</TextBlock.Visibility>
</TextBlock>
When IsCompleted is true, the TextBlock is visible. Otherwise, it is collapsed.
ConvertBack is used when a binding transfers a value in the reverse direction. When reverse conversion is unsupported, the converter should implement suitable behavior for the application's binding requirements.
Interview takeaway: Converters keep presentation-specific transformations separate from the underlying business data.
118. Routed Events vs Commands
Routed Events
Routed events are events that can travel through the WPF element tree.
Examples include button clicks, mouse events, and keyboard events.
Routed Event Example
<Button Content="Save"
Click="SaveButton_Click"/>
private void SaveButton_Click(
object sender,
RoutedEventArgs e)
{
MessageBox.Show("Save clicked");
}
Commands
Commands represent actions that can be invoked by UI elements. They help separate user actions from UI event-handler code.
Examples include Save, Delete, Refresh, and Submit.
WPF provides ICommand, RoutedCommand, and RoutedUICommand.
Command Example
<Button Content="Save"
Command="{Binding SaveCommand}"/>
The ViewModel can expose an ICommand implementation that performs the save operation. The command can also control whether the action is available through CanExecute.
| Routed Events | Commands |
|---|---|
| Represent occurrences, such as clicks. | Represent actions, such as saving data. |
| Commonly use event handlers. | Use ICommand or related command implementations. |
| Can bubble or tunnel through the element tree. | Can support CanExecute and command routing, depending on the command type. |
| Often tied to UI interaction. | Can separate user actions from UI code. |
Interview takeaway: Use routed events for UI event handling and commands for meaningful user actions, especially in MVVM applications.
119. Bubbling Events vs Tunneling Events
Bubbling Events
A bubbling event travels from the originating element upward toward its parent elements.
<StackPanel Button.Click="Panel_Button_Click">
<Button Content="Click Me"/>
</StackPanel>
private void Panel_Button_Click(
object sender,
RoutedEventArgs e)
{
MessageBox.Show("Button click reached the parent");
}
The Button raises a Click event, and the parent StackPanel can handle it.
Tunneling Events
A tunneling event travels from an ancestor toward the originating element. Tunneling event names conventionally begin with Preview, such as PreviewMouseDown and PreviewKeyDown.
<StackPanel PreviewMouseDown="Panel_PreviewMouseDown">
<Button Content="Click Me"/>
</StackPanel>
private void Panel_PreviewMouseDown(
object sender,
MouseButtonEventArgs e)
{
// Runs during the preview route.
}
| Bubbling | Tunneling |
|---|---|
| Starts at the source element. | Starts at an ancestor in the route. |
| Travels toward ancestors. | Travels toward the source element. |
| Useful for parent-level event handling. | Useful for observing or handling input before it reaches the source. |
| Example: Button.Click. | Example: PreviewMouseDown. |
WPF also supports direct routed events, which do not travel through the tree in the same way.
Important: Setting e.Handled = true can prevent later handlers from processing an event normally. Some handlers can still observe handled events when explicitly registered to do so.
120. Container Controls: Grid, StackPanel, and Others
Container controls organize and arrange child elements in a WPF interface.
Grid
Grid arranges elements in rows and columns.
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="Header"
Grid.Row="0"
Grid.ColumnSpan="2"/>
<Button Content="Main"
Grid.Row="1"
Grid.Column="0"/>
<Button Content="Sidebar"
Grid.Row="1"
Grid.Column="1"/>
</Grid>
Auto sizes a row or column to its content, while * allocates a proportional share of the available space.
StackPanel
Arranges children horizontally or vertically.
<StackPanel Orientation="Vertical">
<Button Content="Add"/>
<Button Content="Edit"/>
<Button Content="Delete"/>
</StackPanel>
WrapPanel
Places elements sequentially and wraps them onto additional rows or columns when space is insufficient.
<WrapPanel>
<Button Content="One" Width="100"/>
<Button Content="Two" Width="100"/>
<Button Content="Three" Width="100"/>
</WrapPanel>
DockPanel
Positions children against the top, bottom, left, or right edge.
<DockPanel>
<TextBlock Text="Header"
DockPanel.Dock="Top"/>
<TextBlock Text="Footer"
DockPanel.Dock="Bottom"/>
<TextBlock Text="Main Content"/>
</DockPanel>
Canvas
Positions elements using explicit coordinates.
<Canvas>
<Button Content="Click"
Canvas.Left="50"
Canvas.Top="30"/>
</Canvas>
| Container | Best Use |
|---|---|
| Grid | Forms, dashboards, and row-column layouts. |
| StackPanel | Simple vertical or horizontal sequences. |
| WrapPanel | Wrapping collections of items. |
| DockPanel | Application shells and edge-based layouts. |
| Canvas | Drawing and precise coordinate-based positioning. |
Interview takeaway: Prefer Grid for most structured application layouts. Use StackPanel for simple sequences and Canvas when explicit positioning is required.
Official Documentation
| Array, ArrayList and List :👈 | 👉:WPF QA 121-130 |