WPF Interview Questions And Answers
WPF Interview Questions And Answers
Answer: WPF stands for Windows Presentation Foundation. It's a re-invention of a UI for
Desktop applications using WPF. Apart from dropping controls on "Windows Forms" just as
developers have been doing for years, WPF provides an extra rapid boost to the application
development including Rich User Interface, Animation and much more.
Advantages
Introduction to WPF
If we create a UI with a Button and a TextBox control, the UI looks like the following figure where
the default vertical and horizontal alignment of content of a Button is center. The default vertical
and horizontal alignment of content of a TextBox is left and top.
You want to set the contents of the Button and TextBox to bottom and right.
The code sets VerticalContentAlignment and HorizontalContentAlignmentproperties to
bottom and right.
The best way of defining the resources is on a Window or Page element level. Any resource that
you define for an element also applies to their child elements of that element. For example, if you
define a resource for a Window element that has a Grid as a child element, then the resources
defined for the window elements can also be used by the grid element. However, if you define a
resource for the grid element, then the resource applies only to the child elements of the grid
element.
</elementName>
Where,
elementName: Name of the element that uses the resource.
propertyName: Name of the property that takes its value from the resource.
markupExtension: Define type of resource.
keyName: key name of the resource, which is unique string to identify the resource.
Static Resource
Dynamic Resource
Resources in WPF
Static Resource
Dynamic Resource
Static Resource
We should use the StaticResource markup extension to define the resource as a static resource.
The value of StaticResource is determined at the time of loading.
Let's have a sample program, Add the below code snippet in Window1.xaml file inside the Grid.
1. <Grid.Resources>
2. <SolidColorBrush x:Key="lblbgcolor" Color="Blue"/>
3. </Grid.Resources>
4. <Label Name="lbl" Margin="71,44,77,0" Background="{StaticResourcelblbgcolor}
" Height="49" />
Above code, Grid control uses the Resources property (<Grid.Resources>) to define resource.
SolidColorBrush resource named lblbgcolor defined. lblbgcolor resource is used to set the
background property of lable.
Dynamic Resource
Dynamic Resource we use in a situation where we want to change the value of property at run
time.
Let's have a sample program, Add the following code snippet in Window1.xaml file inside the
Window element.
1. <Window.Resources>
2. <SolidColorBrush x:Key="brush" Color="Red" />
3. </Window.Resources>
4. <Button x:Name="btn" Content="Click Me" Click="Button_Click" Background="{Dy
namicResource brush}" Height="100" Width="100" />
In the above code, Window control uses the Resources property (<Window.Resources>) to
define resource. SolidColorBrush resource named brush defined. Brush resource is used to set
the background property of button.
Resources in WPF
In this case you need to convert the string data to Boolean. This is possible using a Value
Converter. To implement Value Converters, there is the requirement to inherit from I Value
Converter in the System.Windows.Data namespace and implement the two
methods Convert and Convert Back.
Note: In WPF, Binding helps to flow the data between the two WPF objects. The bound object
that emits the data is called the Source and the other (that accepts the data) is called the Target.
Example
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Threading.Tasks;
6. using System.Windows.Data;
7. namespace ValueConverters
8. {
9. public class ValueConverter: IValueConverter
10. {
11. public object Convert(object value, Type targetType, object paramete
r, System.Globalization.CultureInfo culture)
12. {
13. bool isenable = true;
14. if (string.IsNullOrEmpty(value.ToString()))
15. {
16. isenable = false;
17. }
18. return isenable;
19. }
20. public object ConvertBack(object value, Type targetType, object para
meter, System.Globalization.CultureInfo culture)
21. {
22. throw new NotImplementedException();
23. }
24. }
25. }
MVVM was introduced by John Gossman in 2005 specifically for use with WPF as a concrete
application of Martin Fowler's broader Presentation Model pattern. The implementation of an
application, based on the MVVM patterns, uses various platform capabilities that are available in
some form for WPF, Silverlight Desktop/web, and on Windows. Many commercial applications,
including Microsoft Expression products, were built following MVVM.
Advantage of MVVM
Modularity
Test driven approach.
Separation UI and Business layer as view and view model.
Code sharing between pages and forms.
Easy to Maintain.
It separates the business and presentation layers, like MVP and MVC.
Improve Structure/separation of concerns (View, ViewModel and Model).
Enable a better Design/Developer Workflow.
Enhance simplicity and testability.
Enabled by the robust data binding capability of XAML.
No need to use a code behind file (minimalist code-behind file).
Provides application development ability for multiple environments.
Powerful Data Binding, command, validation and much more.
The designer and developer can work together.
But the view model is aware of the needs of the view. They communicate by data binding and a
dependency property or properties.
ViewModel in MVVM
ViewModel is a non-visual class. The MVVM Design Pattern does not derive from any WPF or
Silverlight based class. The ViewModel is unaware of the view directly. Communication between
the View and ViewModel is through some property and binding. Models are connected directly to
the ViewModel and invoke a method by the model class, it knows what the model has, like
properties, methods etcetera and also is aware of what the view needs.
One View-Model can connect to multiple models, work like a one-to-many relationship and
encapsulate business logic and data for the View. A ViewModel inherits some interface
like INotifyPropertyChanged, icommand INotifyCollectionChanged etcetera.
Client
Invoker
Command
Concrete Command
Receiver
Flow of Command Design Pattern
ICommand
ICommand is very simple but it’s more interesting and complicated when you are using it in an
application. ICommand integrates your User Interface to business logic or it’s making a direct
communication between a View to a View Model. It also provides a mechanism for the view to
update the model/view-model.
The Binding keyword looks as in the following image. Here is the binding of TextBox UI controls
with some binding property source object.
In the above sample a TextBox and slider from code behind using some binding property.
Data Binding in XAML (WPF, Silverlight, Windows Phone or Win8 App) Part 1
Triggers are used in styles to perform actions on a change of any property value or event fires.
Triggers create visual effects on controls. By using Triggers we can change the appearance of
Framework Elements.
1. Property Trigger
2. Data Trigger
3. MultiTrigger
4. MultiDataTrigger
5. Event Trigger
Example 1: For example, let's say you have a rectangle control. You want to change the
background color of that control when the mouse hovers over the rectangle control and revert
back when mouse leaves. For this you need to code in the mouse hover event and mouse leave
event of the rectangle control in the backend class for changing the color of rectangle as in the
following code.
In the preceding code you have filled the background color of the Rectangle control by writing
code in two different events, but a trigger helps to overcome this problem by reducing the code.
In other words “Prism is developed by Microsoft Patterns and Practices and provides guidance
designed to help you to more easily design and build rich, flexible and easy-to-maintain Windows
Presentation Foundation (WPF) desktop applications.”.
Introduction to Prism - Composite Application Library (CAL) for WPF and Silverlight
TwoWay: Data moves both directions, if you change it in the source or target it is
automatically updated to the other.
OneWayToSource: Data moves from the target to the source changes to the target
property to automatically update the source property but the target is not changed.
OneTime: Data is changed only one time and after that it is never set again, only the first
time changes to the source property automatically update the target property but the
source is not changed and subsequent changes do not affect the target property.
Data Binding in XAML (WPF, Silverlight, Windows Phone or Win8 App) Part 1
In the MVP pattern the User sends the input to the view, the view forward it to presenter and
presenter then modify the view or the model depending on the type of user action. The view and
the presenter are tightly coupled through bi-directional relationship. The model does not know
about the presenter. The view itself is passive, thats why it's called presenter pattern, since the
presenter pushes the data into the view.
MVC (Model-View-Controller)
In this pattern there is only one controller that gets all the inputs directly, it modifies the data in
the model depending upon the type of the input. Both the model and the view are created by the
controller. The view only knows about the model, but the model does not know about any other
objects.
The Model View ViewModel (MVVM) is an architectural pattern used in software engineering that
originated from Microsoft which is specialized in the Presentation Model design pattern. It is
based on the Model-view-controller pattern (MVC), MVVM is a way of creating client applications
that leverages core features of the WPF platform, allows for simple unit testing of application
functionality, and helps developers and designers work together with less technical difficulties.
MVVM in WPF
Question 14: What are the Templates in WPF ?
Answer: Templates are an integral part of user interface design in WPF. WPF has the following
three types of templates:
Control Template
Items Panel Template
Data Template
Control Template
The ControlTemplate of a control defines the appearance of the control. We can change or
define a new look and appearance of a control by simply changing the ControlTemplate of a
control. ControlTemplates are even more useful when you write your own controls. Using
ControlTemplates, you can build a custom button that has a circular layout and changes its color
when you mouse over or press it.
1. <Grid>
2. <Grid.Resources>
3. <ControlTemplate x:Key="RoundButtonTemplate" />
4. </Grid.Resources>
5. </Grid>
We need to create a circular button where the outer circle of the button is of a different color than
the inner circle and when you mouse over and press the button, it changes the background color.
Add a Grid as contents of the ControlTemplate. Add two Ellipse elements within a Grid with
different radii and different color fills.
1. <Grid.Resources>
2. <ControlTemplate x:Key="RoundButtonTemplate">
3. <Grid>
4. <Ellipse Width="100" Height="100" Name="ButtonBorder" Fill="Oran
geRed" />
5. <Ellipse Width="80" Height="80" Fill="Orange" /> </Grid>
6. </ControlTemplate>
7. </Grid.Resources>
The following code snippet creates a Button element and sets its Template to the
ControlTemplate that we created-
ItemsPanelTemplate
In the previous example, we saw how a Style element can be used within the resources to group
multiple properties of elements and set them using the Style property of elements. However,
Style functionality does not end here. Style can be used to group and share not only properties,
but also resources and event handlers on any FrameworkElement or
FrameworkContentElement.
Styles are resources and used as any other resource and can be applied to the current element,
parent element, root element and even on the application level. The scope if styles are similar to
any other resources. The resource lookup process first looks up for local styles and if not found,
it traverses to the parent element in the logical tree and so on. In the end, the resource lookup
process looks for styles in the application and themes.
The Style element in XAML represents a style. The typical definition of the Style element looks
as in the following:
<Style>
Setters
</Style>
As you can see from the definition of Style, a Style has one more Setter element. Each Setter
consists of a property and a value. The property is the name of the property and the value is the
actual value of that property of the element to that the style will be applied to.
Setters Property
The Setters property of Type represents a collection of Setter and EventSetter objects. Listing 4
uses the Setters property and adds a Setter and EventSetter object.
The code snippet in Listing 4 sets the Setters property of a Style by adding a few Setter elements
and one EventSetter element using XAML at design-time.
1. <Grid>
2. <Grid.Resources>
3. <Style TargetType="{x:Type Button}">
4. <Setter Property="Width" Value="200"/> <Setter Property="Height" Value
="30"/> <Setter Property="Foreground" Value="White"/> <Setter Property
="Background" Value="DarkGreen"/> <Setter Property="BorderBrush" Value
="Black"/> <EventSetter Event="Click" Handler="Button1_Click"/>
5. </Style>
6. </Grid.Resources>
7. <Button>Click me</Button>
8. </Grid>
Templates in WPF
Canvas
DockPanel
Grid
StackPanel
WrapPanel
The purpose and use of these panels is different. Each panel has a different way to position and
reposition child controls placed within that panel. The following articles in this series will
summarise these panels and their usages.
Similar to any other WPF control, a Panel control may be represented in two ways. First, at
design-time using XAML elements and attributes, and second, at run-time, using a WPF class
and its properties.
The code snippet in Listing 2 creates a Grid panel at design-time using XAML.
1. <Window x:Class="CanvasPanelSample.Window1"
2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4. Title="Window1" Height="300" Width="300"
5. Name="RootWindow">
6. <Grid Name="GridPanel" Background="Blue"
7. Width="250" Height="200"
8. VerticalAlignment="Top"
9. HorizontalAlignment="Left"
10. FlowDirection="LeftToRight"
11. />
12. </Window>
The type that defines the Attached Property is designed so that it can be the parent
element of the elements that will set values for the Attached Property. The type then
iterates its child objects using internal logic against some object's tree structure, obtains
the values and acts on those values in some manner.
The type that defines the Attached Property will be used as the child element for a variety
of possible parent elements and content models.
The type that defines the Attached Property represents a service. Other types set values
for the Attached Property. Then, when the element that set the property is evaluated in
the context of the service, the Attached Property values are obtained using internal logic
of the service class.
APs are called “attached” properties because we can attach some behaviour to the control that
is originally not expected from that control.
Example
Suppose I have a TextBox control and I want to extend its functionality to accept letters and
special symbols but not numeric values.
In the code, as we can see, the AP has the default value of False, in other words we need to
provide the APs the value true wherever I want this functionality to work for the TextBox.
The best way of defining the resources is on a Window or Page element level. Any resource that
you define for an element also applies to their child elements of that element.
If you define a resource for the grid element, then the resource applies only to the child elements
of the grid element.
</elementName>
Static Resource
Dynamic Resource
Static Resource
We should use the StaticResource markup extension to define the resource as a static resource.
The value of StaticResource is determined at the time of loading.
1. <Grid.Resources>
2. <SolidColorBrush x:Key="lblbgcolor" Color="Blue"/>
3. </Grid.Resources>
4. <Label Name="lbl" Margin="71,44,77,0" Background="{StaticResourcelblbgcolor}
" Height="49" />
Dynamic Resource
Dynamic Resource we use in a situation where we want to change the value of property at run
time.
1. <Window.Resources>
2. <SolidColorBrush x:Key="brush" Color="Red" />
3. </Window.Resources>
4. <Button x:Name="btn" Content="Click Me" Click="Button_Click" Background="{Dy
namicResource brush}" Height="100" Width="100" />
Resources in WPF
The most basic difference is that StaticResource evaluates the resource one time only, but
DynamicResource evaluates it every time the resource is required. And due to this reason,
DyanamicResource is heavy on the system but it makes pages or windows load faster.
Static Resources
A Static Resource will be resolved and assigned to the property during the loading of the XAML
that occurs before the application is actually run. It will only be assigned once and any changes
to the resource dictionary is ignored.
Your application design concentrates most of its resources into page or application level
resource dictionaries. Static resource references are not re-evaluated based on runtime
behaviours such as reloading a page, and therefore there can be some performance
benefit to avoiding large numbers of dynamic resource references when they are not
necessary per your resource and application design.
You are setting the value of a property that is not on a Dependency Object or a freezable.
You are creating a resource dictionary that will be compiled into a DLL, and packaged as
part of the application or shared between applications.
Dynamic Resources
A Dynamic Resource assigns an Expression object to the property during loading but does not
actually lookup the resource until runtime when the Expression object is asked for the value. This
defers looking up the resource until it is needed at runtime.
The value of the resource depends on conditions that are not known until runtime. This
includes system resources, or resources that are otherwise user settable. For example,
you can create setter values that refer to system properties, as exposed by System
Colours, System Fonts, or System Parameters. These values are truly dynamic because
they ultimately come from the runtime environment of the user and operating system.
You might also have application-level themes that can change, where page-level
resource access must also capture the change.
You intend to adjust the contents of a Resource Dictionary during an application lifetime.
Example
1. <Window.Resources>
2. <SolidColorBrush x:Key="brush" Color="Green" />
3. <Style TargetType="Border" x:Key="PageBackground">
4. <Setter Property="Background" Value="Gold"/>
5. </Style>
6. </Window.Resources>
7. <Grid>
8. <Border Style="{DynamicResource PageBackground}">
9. <Button x:Name="btn" Content="Rajkumar Test" Click="Button_Click" Ba
ckground="{DynamicResource brush}" Height="30" Margin="53,130,85,130" /> </
Border>
10. </Grid>
Code
The type that defines the Attached Property is designed so that it can be the parent
element of the elements that will set values for the Attached Property. The type then
iterates its child objects using internal logic against some object's tree structure, obtains
the values and acts on those values in some manner.
The type that defines the Attached Property will be used as the child element for a variety
of possible parent elements and content models.
The type that defines the Attached Property represents a service. Other types set values
for the Attached Property. Then, when the element that set the property is evaluated in
the context of the service, the Attached Property values are obtained using internal logic
of the service class.
Example
In the code, as we can see, the AP has the default value of False, in other words we need to
provide the APs the value true wherever I want this functionality to work for the TextBox.
Bubbling Events
Tunneling Events
Direct Events
Tunneling Events: Tunneling events are the reverse of the Bubbling events. Tunneling Events
raised first in the controls hierarchy. These events are raised by the Root elements. This allows
events to tunnel down the tree.
Bubbling Events: Bubbling Events are those Events which are first raised by the control than
raised by the other controls in the control hierarchy. It allows Bubble up to the tree till the Root
Element. First Tunneling events are raised then bubbling events raised.
Direct Event: Direct Event is generally raised by the control itself. The behavior of this event is
same as the .NET general event.
See for more details:
Creates two rectangles with same position and sizes accept the second rectangle is rotated at 45
degrees.
1. <Grid>
2. <!-- Original Rectangle -->
3. <Rectangle Width="200" Height="50" Fill="Yellow" />
4. <!-- Rectangle with 45 degrees rotation -->
5. <Rectangle Width="200" Height="50" Fill="Blue" Opacity="0.5">
6. <Rectangle.RenderTransform>
7. <RotateTransform CenterX="0" CenterY="0" Angle="45" /> </
Rectangle.RenderTransform>
8. </Rectangle>
9. </Grid>
The following code snippet changes the values of CenterX and CenterY.
RotateTransform in WPF
1. <Grid>
2. <Grid.Resources>
3. <ControlTemplate x:Key="buttonTemplate">
4. <Grid>
5. <Ellipse Width="160" Height="160" x:Name="outerCircle">
6. <Ellipse.Fill>
7. <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"
>
8. <GradientStop Offset="0" Color="Green"></
GradientStop>
9. <GradientStop Offset="1" Color="Purple"></
GradientStop>
10. </LinearGradientBrush>
11. </Ellipse.Fill>
12. </Ellipse>
13. <Ellipse Width="120" Height="120">
14. <Ellipse.Fill>
15. <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"
>
16. <GradientStop Offset="0" Color="Gray"> </
GradientStop>
17. <GradientStop Offset="1" Color="Blue"> </
GradientStop>
18. </LinearGradientBrush>
19. </Ellipse.Fill>
20. </Ellipse>
21. </Grid>
22. <ControlTemplate.Triggers>
23. <Trigger Property="Button.IsMouseOver" Value="True">
24. <Setter TargetName="outerCircle" Property="Fill" Value="
Black"> </Setter>
25. </Trigger>
26. <Trigger Property="Button.IsPressed" Value="True">
27. <Setter Property="RenderTransform">
28. <Setter.Value>
29. <ScaleTransform ScaleX=".8" ScaleY=".8"> </
ScaleTransform>
30. </Setter.Value>
31. </Setter>
32. <Setter Property="RenderTransformOrigin" Value=".6,.6">
</Setter>
33. </Trigger>
34. </ControlTemplate.Triggers>
35. </ControlTemplate>
36. </Grid.Resources>
37. <Button Template="{StaticResource buttonTemplate}">Click Me</Button>
38. </Grid>
After MouseOver:
See for more details:
ControlTemplate in WPF
The second way is to open the Property Window, select the window style property to either
None, SingleBorderWindow, ThreeDBorderWindow or ToolWindow.
Wiring up an event handler: Attaching event handler in the most cases, for example
Click on Button is easy to do in Visual Studio. However once we understand how events
are wired up in XAML,we'll be able create more sophisticated connections.
Defining resources: Resources are the object which once we define in XAML can be re-
used in the various places inside markup. Resources allow us to centralize and
standardize formatting, and create nonvisual objects such as templates and animations.
Defining control template: WPF controls are designed to be lookless, which means we
can substitute our custom visuals in place of the standard appearance. To do so, we
must create our own control template, which is nothing more than a block of XAML
markup.
Type of XAML
WPF XAML: Encompasses the elements that describe WPF content, such as vector
graphics, controls, and documents.
XPS XAML: It is the part of WPF XAML that defines an XML representation for formatted
electronic documents.
Silverlight XAML: A subset of WPF XAML that's intended for Silverlight applications.
Silverlight is a cross-platform browser plug-in that allows us to create rich web content.
Creating Navigation Paged Application: To create Navigation Window based applications, use
a Navigation Window container instead of a Window container as shown in the following picture
and the source is the property of the Navigation window and write the name of the page that you
want to set as the home page as shown in the following picture:
See for more details:
Creating a ChildWindow:
The ChildWindow element represents a WPF ChildWindow control in XAML. The ChildWindow
control is defined in the System.Windows.Controls namespace.
creates a simple ChildWindow control with its Width, Height, Name, IsModal and Caption
property.
1. PopupChildWindow.Show();
See for more details:
1. Property: A Property specifies the object's appearance or behavior. For example, the
IsEnabled property specifies whether the user can interact with a control or not.
3. Event: An event is related when a control raises one to let your application know that
something has happened. For example TextBox raises a TextChanged event whenever
its text changes.
Code Snippet
TabControl and
TabItem
1. <TabControl>
2. <TabItem Header="Tab 1">xyz</TabItem>
3. <TabItem Header="Tab 2">abc</TabItem>
4. </TabControl>
In WPF, Tabs are very easy to implement. Create a new WPF Window, remove the default Grid
tags, and add the following XAML:
1. <TabControl>
2. <TabItem Header="Tab 1">xyz</TabItem>
3. <TabItem Header="Tab 2">abc</TabItem>
4. </TabControl>
1. Window.Clip>
2. <EllipseGeometry Center="150,160" RadiusX="120" RadiusY="120" />
3. </Window.Clip>
1. <Image Source="Garden.jpg">
2. <Image.Clip>
3. <EllipseGeometry Center="150,160" RadiusX="120" RadiusY="120" />
4. </Image.Clip>
5. </Image>
1. private void ClipImage()
2. {
3. // Create a BitmapImage
4. BitmapImage bmpImage = new BitmapImage();
5. bmpImage.BeginInit();
6. bmpImage.UriSource = new Uri(@ "C:\Images\Garden.jpg", UriKind.RelativeO
rAbsolute);
7. bmpImage.EndInit();
8. // Clipped Image
9. Image clippedImage = new Image();
10. clippedImage.Source = bmpImage;
11. EllipseGeometry clipGeometry = new EllipseGeometry(new Point(150, 160),
120, 120);
12. clippedImage.Clip = clipGeometry;
13. LayoutRoot.Children.Add(clippedImage);
14. }
So, whenever data travels from source to target, it can be transformed in two ways:
1. Data value: Here the transformation will be done with just the value by keeping the data
type intact. For example, for number fields, you can transform a value from a floating
point number to an integer by keeping the actual value as a float.
2. Data type: One can also transform the data type. For example, setting a style based on
some Boolean flag.
Defining a converter
Defining any converter requires implementation of an IValueConverter interface in a class. This
interface has the following two methods:
How to use
Once your class is part of a ResourceDictionary, you can point to the instance of the converter
using the Converter property of Binding, along with a StaticResource markup extension.
To implement an IValueConverter one must create a class and then put the instance of that class
in a ResourceDictionary within your UI.
Converters in WPF
Default: This is the default value and it means a lost focus for most of the controls.
LostFocus: Value update will be on hold until the focus moves out of the control.
PropertyChanged: Value update will happen whenever a target property changes. It
usually happen on every keystoke.
Explicit: Used to defer source updates until the user does it forcibly by the click of a
button or so.
Default vs LostFocus
Default and LostFocus means the same thing for most of the controls with the exception of
DataGrid. For DataGrid:
Code
1. <grid>
2. <Grid.ColumnDefinitions>
3. <ColumnDefinition Width="50*" />
4. <ColumnDefinition Width="50*" />
5. </Grid.ColumnDefinitions>
6. <TextBlock Text="Source:" Width="auto" />
7. <TextBox Name="SourceText" Width="160" Height="30" Margin="48,0,44,82" /
>
8. <TextBlock Text="Target:" Grid.Column="1" Width="auto" />
9. <TextBox Name="TargetText" Width="160" Height="30" Text="{Binding Elemen
tName=SourceText, Path=Text,UpdateSourceTrigger=Default}" Grid.Column="1" Ma
rgin="44,0,47,82" />
10. </grid>
Output
The HorizontalAlignment enumeration has the four properties Left, Center, Right and Stretch.
The Left, Center and Right properties sets a child element to left, center and right of the parent
element. The Stretch property stretches a child element to fill the parent element's allocated
layout space.
Example
1. <StackPanel Background="LightGray">
2. <Button Name="Rect1" Background="LightBlue" Width="150" Height="50" Hori
zontalAlignment="Left" Content="Left Aligned" />
3. <Button Name="Rect2" Background="LightGreen" Width="150" Height="50" Hor
izontalAlignment="Center" Content="Center Aligned" />
4. <Button Name="Rect3" Background="LightCyan" Width="150" Height="50" Hori
zontalAlignment="Right" Content="Right Aligned" />
5. <Button Name="Rect4" Background="LightPink" Height="50" HorizontalAlignm
ent="Stretch" Content="Stretch Aligned" />
6. </StackPanel>
The VerticalAlignment property is a type of HorizontalAlignment enumeration and represents
how a child element is positioned within a parent element vertically.
The VerticalAlignment enumeration has the four properties Top, Center, Bottom and Stretch.
The Top, Center and Bottom properties set a child element to top, center or bottom of the parent
element. The Stretch property stretches a child element to fill the parent element's allocated
layout space vertically.
Example
1. <Grid>
2. <Grid.ColumnDefinitions>
3. <ColumnDefinition Width="100" />
4. <ColumnDefinition Width="100" />
5. <ColumnDefinition Width="100" />
6. <ColumnDefinition Width="100" />
7. </Grid.ColumnDefinitions>
8. <Button Name="Button1" Background="LightBlue" Height="30" Width="100" Ve
rticalAlignment="Top" Content="Left Aligned" />
9. <Button Name="Button2" Background="LightGreen" Height="30" Width="100" G
rid.Column="1" VerticalAlignment="Center" Content="Center Aligned" />
10. <Button Name="Button3" Background="LightCyan" VerticalAlignment="Bottom"
Height="30" Width="100" Grid.Column="2" HorizontalAlignment="Left" Content="
Right Aligned" />
11. <Button Name="Button4" Background="LightPink" Content="Stretch ligned" W
idth="100" Grid.Column="3" HorizontalAlignment="Stretch" />
12. </Grid>
See for more details:
Tool tips are used to help the users to learn the purpose of Controls in many Windows-based
programs. Tooltips are nothing but small rectangles that appear when the user hovers the mouse
pointer over the Control. The rectangle contains a short piece of text describing the control. Once
displayed, the tips disappear when the user moves the mouse pointer away from the linked
control or clicks a mouse button, or after a short delay.
ToolTip Example: Drag a Button control from the toolbox and drop it. Add a ToolTip property to
the button with a message you want to show on mouse hover of the button. We can add a
ToolTip in two ways. First the button shows the simplest way to display a ToolTip. The second
method is preferred for creating a customized ToolTip.
ToolTip in WPF
<ListBox></ListBox>
The Width and Height properties represent the width and the height of a ListBox. The x:Name
property represents the name of the control, which is a unique identifier of a control. The Margin
property sets the location of a ListBox on the parent control. The HorizontalAlignment and
VerticalAlignment properties are used to set horizontal and vertical alignments.
The code sets the vertical and horizontal alignment of the ListBox and sets the margin.
ListBox in WPF
<Popup></Popup>
The Width and the Height properties represent the width and the height of a Popup. The Name
property represents the name of the control that is a unique identifier of a control. The Margin
property is used to set the location of a Popup on the parent control. The HorizontalAlignment
and VerticalAlignment properties are used to set horizontal and vertical alignments.
The following code snippet sets the name, height, and width of a Popup control. The code also
sets horizontal alignment to left and vertical alignment to top.
Open a Popup: The Popup Control displays its contents when IsOpen set true.
Closing a Popup: The Popup Control displays its contents when IsOpen is set to false.
1. privatevoid Popup_Ok_Click(object sender, RoutedEventArgs e)
2. {
3. Popup1.IsOpen = false;
4. }
WPF Popup
Add a click event to the button. Replace the Button's XAML with the following:
When the program is executed the window that appears similar to the image below:
Tight multimedia integration: To use 3-D graphics, video, speech, and rich document
viewing in Windows 32 or Windows Forms applications, you would need to learn several
independent technologies and blend them together without much built-in support. WPF
applications allow you to use all these features with a consistent programming model.
Resolution independence: WPF lets you shrink or enlarge elements on the screen,
independent of the screen's resolution. It uses vector graphics to make your applications
resolution-independent.
Hardware acceleration: WPF is built on top of Direct3D, which offloads work to graphics
processing units (GPUs) instead of central processor units (CPUs). This provides WPF
applications with the benefit of hardware acceleration, permitting smoother graphics and
enhanced performance.
Rich composition and customization: WPF controls are easily customizable. You
need not write any code to customize controls in very unique ways. WPF also lets you
create skins for applications that have radically different looks.
Easy deployment: WPF provides options for deploying traditional Windows applications
(using Windows Installer or Click Once). This feature is not unique to WPF, but is still an
important component of the technology.
Culturally aware controls: Static text in controls and the return data for the String
function are modified according to the culture and language specified by the end user's
operating system.
Disadvantages
WPF's in-box control suite is far more limited than that of WinForms.
There's greater support in the 3rd-party control space for WinForms. (That's changing,
but for now by advantage of time, WinForms has greater support in the community).
Most developers already know WinForms; WPF provides a new learning curve.
Although these assemblies provide hundreds of types within numerous namespaces, consider
this partial list of WPF namespaces:
You will encounter other namespaces during the remainder of this class.
Again, consult the .NET Framework SDK documentation for full details.
Creating an AccessText
<AccessText>_Click Me</AccessText>
The following code snippet adds an AccessText to a Button control. The button control click
event will be raised when you select the ALT+C keys on the keyboard.
If there are multiple underscore characters, only the first one is converted into an AccessKey; the
other underscores appear as normal text. If the underscore that you want converted to the
access key is not the first underscore, use two consecutive underscores for any underscores that
precede the one that you want to convert.
WPF AccessText
1. SolidColorBrush
2. LinearGradientBrush
3. RadialGradientBrush
4. DrawingBrush
5. Visual Brush
6. ImageBrush
Brushes in WPF
Bitmap effects enable designers and developers to apply visual effects to rendered Microsoft
Windows Presentation Foundation (WPF) content. For example, bitmap effects allow you to
easily apply a DropShadowBitmapEffect effect or a blur effect to an image or a button. The
unmanaged APIs provide an extensible framework for independent hardware vendors (IHVs) to
develop custom effects to use in WPF applications.
1. BlurBitmapEffect
2. OuterGlowBitmapEffect
3. DropShadowBitmapEffect
4. BevelBitmapEffect
5. EmbossBitmapEffect
Each bitmap effect has properties that can control the filtering properties, such as Radius of
BlurBitmapEffect.
<TreeView></TreeView>
A TreeView control hosts a collection of TreeViewItem. The Header property is the text of the
item that is displayed on the view. The following code snippet adds a parent item and six child
items to a TreeView control.
The above code removes root items from the TreeView, not the subitems. To remove sub items,
first we need to find the selected item and then we need to call TreeViewItem.Items.RemoveAt
method.
Application Commands
Edit Commands
Component Commands
Media Commands
XAML
1. <StackPanel>
2. <Menu>
3. <MenuItem Command="ApplicationCommands.Paste" /> </Menu>
4. <TextBox />
5. </StackPanel>
C#
Commands in WPF
The panel is typically used to group 2D graphic elements together and not to layout user
interface elements. This is important because specifing absolute coordinates brings you in
trouble when you begin to resize, scale or localize your application. People coming from
WinForms are familiar with this kind of layout - but it's not a good practice in WPF.
In WPF, a Canvas Panel has a very simple layout. We can position any object using its two
properties:
Canvas.Left
Canvas.Top
Note: A Canvas panel does not resize automatically when our normal application resizes in the
browser.
Creating a TextBlock
<TextBlock/>
The Width and Height attributes of the TextBlock element represent the width and the height of a
TextBlock. The Text property of the TextBlock element represents the content of a TextBlock.
The Name attribute represents the name of the control, which is a unique identifier of a control.
The Foreground property sets the foreground color of contents. This control does not have a
Background property.
WPF TextBlock
The WPF TabControl allows you to split your interface up into different areas, each accessible by
clicking on the tab header, usually positioned at the top of the control. Tab controls are
commonly used in Windows applications and even within Windows' own interfaces, like the
properties dialog for files/folders etc.
Just like with most other WPF controls, the TabControl is very easy to get started with. Here's a
very basic example:
The DockPanel makes it easy to dock content in all four directions (top, bottom, left and right).
This makes it a great choice in many situations, where you want to divide the window into
specific areas, especially because by default, the last element inside the DockPanel, unless this
feature is specifically disabled, will automatically fill the rest of the space (center).
Preview
See for more details:
DockPanel in WPF
<StatusBar></StatusBar>
The Width and Height properties represent the width and the height of a StatusBar. The Name
property represents the name of the control that is a unique identifier of a control.
The following code snippet creates a StatusBar control and set its content to some text.
In other words, A polyline is a collection of connected straight lines. The Polyline object
represents a polyline shape and draws a polyline with the given points. The Points property
represents the points in a polyline. The Stroke property sets the color and StrokeThickness
represents the width of the line of a polyline.
Creating a Polyline: The Polyline element in XAML creates a polyline shape. The following code
snippet creates a polyline by setting its Points property. The code also sets the black stroke of
width 4.
1. <Polyline
2. Points="10,100 100,200 200,30 250,200 200,150"
3. Stroke="Black"
4. StrokeThickness="4" />
The Polyline element in XAML creates a polyline shape. The following code snippet creates a
polyline by setting its Points property. The code also sets the black stroke of width 4.
1. <Polyline
2. Points="10,100 100,200 200,30 250,200 200,150"
3. Stroke="Black"
4. StrokeThickness="4" />