0% found this document useful (0 votes)
81 views

C# - WINDOWS PRESENTATION FRAMEWORK

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views

C# - WINDOWS PRESENTATION FRAMEWORK

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 87

Unit – II Introduction to Windows Programming:creating windows

forms, windows controls, menus and dialogue boxes, overview of


xml.Window programming vs.Window presentation
foundation,main features of WPF 4.5, WPF 4.5architecture, WPF
4.5class hierarchy, types of WPF applications, WPF4.5 designer
interface, Using XAML in WPF 4.5 applications, WPF properties,
WPF events,working with dialog boxes in WPF application,
compiling and running WPF 4.5 applications, WPF 4.5controls,
resources, styles, templates, commands.

UNIT -2
INTRODUCTION TO WINDOWS PROGRAMMING

❖​CREATING WINDOWS FORMS


▪​ WINDOWS FORMS APPLICATION: windows forms is the vital
components for the design of window application. In C#, windows
forms or application use System.Windows.Forms.namespace.
▪​ FORM :it is a graphical container, which contain the graphical
controls like labels, textboxes, buttons, listboxes etc.
▪​ It is also called window
▪​ It has the visual appearance with a title bar, icon control box(with
minimize, maximize& close button).
▪​ CREATING WINDOWS FORM APPLICATION
1.​ Open MS visual studio.
2.​ Click on file → new → project.
3.​ Select language as VC#.
4.​ Select type as “windows forms application”
5.​ Enter name & location of the project.
6.​ Click on “ok”.
(This will create a windows forms appln with name form:
▪​ DEVELOPMENT OF A FORM – includes 2 stages
1.​ Designing
2.​ Coding
1.​ Designing the form:
Drag & drop the controls from the “toolbar”, select the required
controls & set the properties
Ex: form 1- Text: login
Label1- text: user name Label2 -Text: password
Text box1-(no properties required) Text box2-password char*
button1-text : ok button2-text: cancel

Before setting properties after setting properties


(The above process is called form designing)
2.​ Coding the form:
Double click on the control & write the code in the “code windows”.
Eg: double click on “ok” button then button code automatically
gets on window after that write the following code.
PROGRAM
Private void button1-_click (object sender, event args e)
{
If (textbox1. Text = “system” && textbox2. Text ==
“manager”)
MessageBox. Show(“login is successful”);
Else
MessageBox. Show(“invalid login”);
}
//double click on “cancel” button & write the following code
Private void button2_click(os, ea e)
{
Applicaton. Exit( );
}
▪​ The above process is called “form coding”
▪​ In C# every form is a class, so that at runtime we can create any
no of forms.

▪​ Automated generated code:


- While we design the controls, the visual studio generates some
automatic code in “form1. Designer.cs” file.
▪​ To open this flie, open solution explorer, expand form1 then
double click on “form1.Designer. cs”.
▪​ When we design the form the code will be automatically
generated in a method called “Initialize component( )”.
-​ Every form contains 2 flies
1. Form1. Designer.cs- contains the code for designing
(automatically generated code by VS)
2. Form1.cs- contains the actual functionality code (written by
programmer)
▪​ Common properties for all the controls
1. Name 2.Text, 3. Back color 4. Fore color 5. Font, 6. Enabled,
7. Visible, 8. Cursor(specifies mouse points style), 9. Size (width &
height of component), 10. Location(x& y co-ordinates of controls
pos), 11. Textalign, 12. Image,
13. Image align, 14. Context menu strip(ref of the respective
context menu control).
▪​ Common event for all the controls:
1. Click, 2. double click, 3. mouse move, 4. mouse enter, 5. mouse
leave, 6. key press, 7. enter, 8. leave.
▪​ Event – runtime action that can be performed by the user.
▪​ Event handler – syntax: Private void control name – event name
(OS, EA e)
{ //code
}
▪​ Implementation of event handler:
▪​ First in the design window, select the form or control, for which u
want to create the event handler.
▪​ Open “properties” window & click on “Events” option.
▪​ Select the required event; for which u want to create the event
handler, press enter.
▪​ Then the event – handler will be created in the code window
▪​ Demo on event handling
DESIGN:
Button1: Text: CLICK ME
Backcolor: Red
Forecolor: Blue

▪​ PROGRAM
Private void button1_click (OS, EA e)
{
Messagebox.Show (“button clicked”)
}
Private void button1_mouse enter(OS, EA e)
{
Button1. Backcolor= color.Yellow;
Button1. Forecolor= color.Dark red;
}
Private void button1_mouse leave(OS, EA e)
{
Button1. Forecolor=color. Dark red;
Button1. Backcolor= color. Yellow;
}
▪​ Working with multiple forms
1. Adding a new form to the project
- In the “solution explorer” right – click on the project & choose
“Add→
windows form”.
-In the dialog box, enter the name of the new form.
-Then the new form will be created.
2. Deleting a form from the project:
In the “solution explorer” right-click on the required from click
“delete” option, click ok
▪​ Changing startup form:
▪​ Even if, u can add multiple forms to the project “form1” is opened
by default(when the proj is started). This is called “startup form”.
▪​ To change the startup form, change the following statement with
the required class name in the “program class’s main ( ) method.
▪​ Syntax: Application. Run(new< form name> ( ));
Eg: Application.Run(new form2( ));
▪​ To invoke forms at runtime (programmatically)
▪​ Create an object for the form class
Form name object= new form Name( );
Object.Show( );
Eg: handling multiple forms
Form1. Cs
Private void form1 – double click(OS, EA e)
{
Form2 f= new Form2( );
}

▪​ Controls in windows application:


Control class is the base class for windows controls.
1. Common controls- 1. Button, 2.label, 3.TextBox, 4.CheckBox,
5.RadioButton, 6.ComboBox, 7.ListBox, 8.PictureBox, 9.LinkLabel,
10.DomainUpDown,11.NumericUpDown, 12.
DateTimePicker,13.MonthCalendar.
2. Menu controls- 1.MenuStrip, 2.ContextMenuStrip
3. Dialog box controls- 1.ColorDialog, 2.FontDialog,
3.FolderBrowserDialog, 4.OpenFileDialog,
5.SaveFileDialog, 6.PrintDialog.
1. COMMON CONTROLS
1.​ Buttons - popular, action based control
-​ executes an operation, when it is clicked.
API – System.Windows.Forms.Button
2.​ Label - passive, presentation purpose.
3.​ Text box - multiline, scrollbar, read-only & many attributes
-​ enter up to 2,048 chars.
-​ If u set multiline property to true – 32 KB can be entered.
-​ Used to accept password by using password char property to mask
chars.
-​ We can also restrict text from being entered in a textbox control by
creating an event handler for KeyDown event.
●​ Assigning text:
PROGARM: Private void button1 – click(OS, EA e) {
TextBox1.Text= “welcome”; //no set text method
}
//Adding string : String S1= “ ”;
S1 = textBox1.Text;
//Adding scrollbars: there are 4 ways to add scroll bars to a text
box 0- none, 1- horizontal, 2- vertical, 3- both
//Aligning text: by text align property 0- left justified, 1- right
justified
2- centered
//Controlling i/p: we can restrict user i/p by using key press event
& check the key that was typed, which is passed as e.KeyChar,
Private void textbox1_keypress(OS, EA e)
{
If (e. Key char < ‘0’ || e. Key char> ‘9’)
MessageBox.Show( “enter digits only”);
}
-​ Rich text boxes: rich text with formatting – fonts, colors, links,
bold, italic similar to word processors.
4.​ Link labels – based on label class and support web-style
hyperlinks.
5.​ CheckBox – used to take the choice from user &can be 2 stated
checked/unchecked.
Event – checked changed, By default 2 states
3-states for check boxes: checked, unchecked, indeterminate.
6. RadioButton – option button – similar to check boxes except,
they are round,
where check boxes are square
Used together in groups (when one is selected in group, others
are automatically deselected)
-​ Property – checked
-​ Event – checked change
7. ComboBox: display data in a drop-down combo box. The combo
box is made up of 2 – parts. The top part is a text box that allows
the user to type in all or part of a list item. The other part is a list
box that displays a list of item from which we can select an item.
- Event – selectedIndexChanged
- Methods: Add, insert, Remove At, clear, Index Of
8. ListBox: display a list of items from which the user can select 1
or more.
-​ Selection mode – none – no item can be selected
-​ One – single item can be selected
-​ Multi simple – multiple item can be selected(directly by clicking on
item)
-​ Multi extended – multiple item can be selected(with shift+ click,
CTRL+click)
-​ Events of list – SelectedIndexChanged
-​ Method of list box- Add, insert, remove AT, clear, index Of
-​ ListBoxName.Item.Add(“apple”); - adds an item at the end of a list.
9. pictureBox- displays images
10. MonthCalender- displays calendar
11. NumericUpDown- u can click arrows present in keyboard
12. DomainUpDown- spin box(windows control equipped with 2
opposite arrow buttons)
13. DateTimePicker- allows you to pick date& time from popup
calendar
Syntax: DateTimePicker1.value=DateTime.Today;

2. MENU CONTROLS
1. Menu strip: Menus are control that allow the user to make
selections
made up of ToolStripMenuItem (individual parts of a menu)
-​ Used to create a menu bar in the form
-​ File Edit View Tool Help // MENU
-​ API – System.Windows.Forms.MenuStrip
-​ Naming convention- Mnuxxxx
-​ Each menu item will be created as a control for
“ System.Windows.Forms.ToolStripMenuItem” class.
-​ Naming convention – “xxx tool strip Menu Item”.
●​ Properties of menu strip-Dock – Top, bottom, left, right,
fill(remains in contact with that edge)
-​ Text Direction – horizontal, vertical 90, vertical 270
-​ Events- Item clicked, (click, double clicked, mouse move, mouse
enter, mouse leave, key press, enter, leave)
●​ Properties of Menu Item: all common properties
-​ Event: click, double click, mouse move, mouse enter, mouse leave.

//CODE: double click on menu item to open click event and write
code
Private void NewToolStripMenuItem_click( OS, EA, e)
{
Message box.Show(“selected/clicked new”);
}
Similarly Write for open, cut, copy
Private void ExitToolStripMenuItem_click(OS, EA, e)
{
Application. Exit ( );
}
▪​ Creating submenus: When a menu item has a submenu, a right
pointing arrow
( ) appears in that menu item at runtime.
-​ To create submenus – just create the menu item & then select it in
a form designer.
-​ Doing so, opens a “type here” box to the right of that menu item &
enter the caption for the sub menu item.
-​ Then double click on submenu Item to open their click event &
write code.

▪​ Creating menu access key: To select Menu Item from keyboard


using ALT key (ALT+F - file menu, ALT+X - EXIT).
-​ To give an access key, precede the access key in its caption with
an ampersand(&).
-​ EX: “&file”, “E&XIT”. The accesskey are underlined in menu
caption.
▪​ Creating menu shortcuts – u can set a short cut with the ShortCut
property.
-​ To show & hide menu items, use their visible property.

2. Context Menu Strip: are used to give access to frequently used


menu commands & u can bring them up by right-clicking another
control.
- We can use context menus to display control-specific option such
as cut, copy & paste in text boxes.
- We can associate context menus with other control by setting the
control’s context Menu Strip property to context Menu control.
- we can add menu items to a contexts at design time or in code
by creating - Menu Item objects & adding them to Menu Items
collection.
- Context Menu Item can be disabled, hidden or deleted.
- Context Menus are not divided into separate menus like File, Edit
& window.
- NOTE: context Menu would be displayed, when the user right
clicks on a control or a form, at runtime.
- The context menu is also called as short cut menu. It is an
invisible control.
●​ Creating context menu strip: Same as standard menu
-​ you need to add a context menu strip control to a windows from.
-​ The caption is “Context Menu” & give the items in the menu.
-​ The connect code to the context Menu Items with any click events.
-​ Private void cut Tool Strip Menu Item – click (OS, EA e)
{
Message Box. Show(“selected cut .....”):
}
Similarly write code for copy, paste
-​ Finally, assign the context menu control such as control Menu
Strip1 to context Menu Strip property of the control u want to
connect,
-​ For eg: connect context Menu to multiline text box, when the
uses right-clicks this text box.
-​ A context menu can be associated with a number of other control,
but each control can have only one context menu.

3.Dialog boxes:
- There are number of built-in dialog boxes in C#, which are
essential. There are many dialog such as,
1. Open file dialogs
2. Save file dialogs
3. Font dialogs
4. Color dialogs
5. Print dialog
6. Print preview dialogs
7.page setup dialogs
- We can use the show dialog method to display the dialog at
runtime.
- Possible return values from Dialog Result Enumeration (Abort,
Ignore, No, Ok, Retry, Yes).
- Dialog controls are meant for creating dialog boxes at runtime.
- A dialog box can be defined as a “force responsive window”,
which requests the user’s attention at runtime.
- That means without answering the dialog box, the user can’t
work with the form.
- All the dialog box controls are known as “invisible control”.
- .Net offers several dialog box controls.
1.​ Color dialog - displays a dialog box, for a color selection.
-​ API- System.Windows.Forms.ColorDialog
-​ To invoke the dialog box at runtime: ColorDialog1. ShowDialog
-​ To get the currently selected color: ColorDialog1.Color
Private void button back color_click(OS, EA, e)
{
Clr dlg back. Show Dialog( );
this. Back color= clr dlg back clr. Color;
}
2.​ Font dialog: displays a dialog box, for a font select, with font
name, font style(bold, italic,....), font size options.
Private void btn font- click(OS, EA, e)
{
Font Dialog1. Show Dialog( );
Text box1. Font= font Dialog1. Font;
}

3.​ Folder browser dialog: displays a dialog box, for a folder selection.
-​ To invoke dialog box – FolderBrowserDialog1.ShowDialog( );
-​ To get the currently selected folder’s full path
FolderDialog1.Selected Path;
4.​ Open File Dialog: displays a dialog box, for a file selection to open
a file.
-​ To get the currently selected file path & name
Open File Dialog1. File Name;
Demo on open file dialog:
DESIGN: label1: name:lb1filenm text: enter file name
TextBox1: name:txtFilename
Button1:name: btnbrowser text: browser
Button2:name: btnopen text: open
TextBox2:name: txtconent Readonly:true
MultiLine:True WordWrap:False ScrollBars: both
Drag &drop open file dialog from toolbox

PROGRAM:
Using System.IO;
Private void btn open click(OS, EA e)
{
String file name= txt file name. Text;
File Info fobj= new File Info(file name);
If (fobj. Exists)
{{
Stream reader sr=new stream reader (file name);
String content=sr.read To End( );
Txt content. Text= content;
Sr. Close( );
}
Else
Message Box. Show (“file not found”);
}
Private void btn browser-click(OS, EA, e)
{
Open File Dialog1. Reset( );
Open File Dialog1. Show Dialog( );
Txt File name. Text=open File Dialog1. File name;
}

5.​ Save File Dialog:


-​ Display a dialog box a file a selection,
-​ API – system.Windows.Forms.SaveFileDialog
-​ To get the currently selected file path & name.
Save File Dialog1. File name;
DESIGN
label1: name:lb1filenm text: enter file name
TextBox1: name:txtFilename
Button1:name: btnbrowser text: browser
Button2:name: btnopen text: open
Text box2: Name: txt content, Multi line: True
Word wrap: False, Scroll bars: Both
PROGRAM
Using System.IO;
Private void btn browser_click(OS, EA, e)
{
SaveFileDialog1.Reset( );
SaveFileDialog1.ShowDialog( );
Txt file name. Text= SaveFileDialog1.File name;
}
Private void btn save_click(OS, EA, e)
{
String file name= txt file nm. Text;
if(file name!= “ ”)
{
File Info fobj= new File Info(file name);
if(!fobj. Exists)
{
Stream writer sw= new stream writer(filename)
String content= txt content. Text;
Sw. Write(content);
Sw. Close( );
MessageBox. Show(“successfully saved”);
}
Else
MessageBox.Show(“file already exists”);
}
Else
Message box. Show(“select any file name first”);
}

6.​ Print dialog: displays a dialog box, for printing preferences


selection like number of copies, name of the printer paper range &
paper orientation etc.
-​ To get the selected printer setting:
Print Dialog1. PrinterSettings;
DESIGN:
label1: name:lb1filenm text: enter file name
TextBox1: name:txtFilename
Button1:name: btnprint text: print
Button2:name: btnbrowser text:browser
PROGRAM:
Using system. Drawing. Printing;
Using system. Io;
Private void btn browser – click(OS, EA ,e)
{
Open File Dialog1. Reset( );
Open File Dialog1. Show Dialog( );
Txt file name. Text= open File Dialog1. File name;
}
Private void btn print – click(OS, EA, e)
{
String file name= txt file name. Text;
If(file name != “ ”)
{
File Info fobj= new File Info(file name);
If (fobj. Exists)
{
Print Dialog1. Rest( );
Print Dialog1. Show Dialog( );
Print Document doc= new print document( );
Doc. Print Settings= print Dialog1. Printer setting;
Doc. Document Name= file name;
Doc. Print ( );
Message box. Show(“printing started”);
}
Else
Message box. Show(“file not found”);
}
Else
Message box. Show(“enter file name”);
}

❖​OVER VIEW OF XML:


-XML stands for Extensible Mark up Language. It is text based
language derived from standard generalized Mark up
Language(SGML).
- XML tags identify the data & are used to store & organize the
data, rather than specifying how to display it like HTML tags, which
are used to display the data.
- XML is not going to replace HTML, but it introduces new
possibilities by adopting many successful features of HTML.
-​ 3 important characteristics of XML:
1. XML is extensible – allows u to create yours own self- descriptive
tags or language, that suits yours application.
2. XML carries the data, does not present it – XML allows u to store
the data irrespective of how it will be presented.
3. XML is a public std: XML was developed by an organization
called world wide web consortium(W3C) & is available as an open
std.
-​ XML usage:
-​ XML can work behind the scene to simplify the creation of TML
documents for large websites.
-​ XML can be used to exchange the info b/w organization & systems.
-​ XML can be used for offloading & reloading Databases.
-​ XML can be used to store & arrange the data, which can customize
data handling needs.
-​ XML can be merged with style sheet to create designed o/p.
-​ Virtually, any type of data can be expressed as an XML document.
-​ What is mark up?
XML is a mark up language that defines set of rules for encoding
documents in a format that is both human readable & machine
readable.
Mark up is info added to a doc that enhances its meaning in certain
ways,(it identifies the parts & how they related to each other).
A mark up language is a set of symbols that can be placed in the
text of a doc to demarcate & label the parts of that doc.
<message>
<text> Hello, world! </text>
</message>
<message>, </text> are tags.
XML is not a PL. It is stored in a dimple text file & is processed by
special s/w that is capable of interpreting XML.
●​ XML – syntax
<?xml version= “1.0”?>
<content – info>
<name> xyz </name>
<company> osmania</company>
</content – info>
-​ There are 2 kinds of info, in the above file
1. Mark up like <content – info>
2. The text or char data, xyz

▪​ Syntax rules to write diff types of mark up & text in XML


doc:

1. XML declaration: XML document can optionally have an xml


declaration.
-​ <?xml version= “1.0” encoding= “UTF – 8”?>
-​ Version is xml version & encoding specifies char encoding used in
document.
-​ XML declaration is case sensitive & must being with “<?xml>”
where “xml” is written in lower-case.
-​ if document contains XML declaration, then it strictly need to be
the first statement of xml document
-​ the XML declaration strictly needs be the first statement in xml
doc.
2. Tags & Elements:
-​ An XML file is structured by several xml-elements, also called XML
– nodes or xml – tags. The name of xml elements are enclosed in
triangular brackets.
-​ Syntax: <element> ........</element>
-​ Nesting of elements: XML element can contain multiple xml
elements as its children, but children elements must not overlap.

-​ Root elements: Xml doc can have only one root element
<root>
<x>.....</x>
<y>....</y>
</root>
-​ The names of xml elements are case-sensitive.
3. XML attributes: Specifies a single property for the element,
using a name/value pair.
-​ Attribute names in xml are case-sensitive.
-​ Same attribute cannot have 2 values in a syntax
<a b= “X”>.....</a>

Syntax Rules for XML Attributes


●​ Attribute names in XML (unlike HTML) are case sensitive. That
is, HREF and href are considered two different XML attributes.
●​ Same attribute cannot have two values in a syntax. The following
example shows incorrect syntax because the attribute b is specified
twice
●​ <a b=”x” c=”y” b=”z”>…..</a>
●​ Attribute names are defined without quotation marks, whereas
attribute
Values must always appear in quotation mark
●​ <a b = x>…</a>
4. XML references: Allow you to add or include additional text or
mark up in an xml doc refs always begin with “&” end with “;”.
-​ Xml has 2 types of refs.
1.​ Entity references: contains a name b/w the start & end delimit for
example &amp;
2.​ Char refs: &#65; the number always refer to unicode of a char.
65 refer to alphabet “A”.
5. Xml text:
-​ The names of XML-elements and XML-attributes are case-sensitive,
which means the name of start and end elements need to be
written in the same case.
-​ To avoid character encoding problems, all XML files should be
saved as Unicode UTF-8 or UTF-16 files.
-​ Whitespace characters like blanks, tabs and line-breaks between
XML-elements and between the XML-attributes will be ignored.
-​ Some characters are reserved by the XML syntax itself. Hence, they
cannot be used directly. To use them, some replacement-entities
are used, which are listed below
Not Replacement Character
Allowed Entity Description
Character

< &lt; less than

> &gt; greater than

& &amp; ampersand

' &apos; apostrophe

" &quot; quotation


mark
❖​WPF v/s windows forms:
-​ WPF is a graphical subsystem .it is used in order to render user
interfaces in window based applications.
-​ WPF (Avalon) was released as part of .Net framework, version 3.0.
it enables modern UI features.
-​ UI features- transparency, gradients & transforms.
-​ it is a consistent programming model for building applns, and
provides a definite separation b/w user interface & the business
login.
-​ Windows forms is a graphical application programming
interface(API). it is a feature of windows .Net framework and
provides access to the native Microsoft windows interface
elements.
-​ It is a replacement for a C++ based MS foundation class library. It
does not provide a model that is comparable to MVC.
-​ WPF offers a new markup alternative, which is known as XAML. An
appln that is defined as WPF is able to be deployed on the desk
top or hosted on a web browser.
-​ it is also able to handle rich control, design & development of
visual aspects of programs run by windows. Its goals are
specifically to unify a no.of appln services, including user
interfaces, 2d & 3d drawings, fixed & adaptive docs, advanced
typography, vector graphics, raster graphics, animation, data
binding, audio & video.
-​ Windows forms is an event-driven appln that is supported by MS
.net framework.
❖​INTRODUCING WPF(windows presentation foundation)
❖​NEW FEATURES OF WPF 4.5
-​ WPF 4.5 is a UI framework that helps u in creating standalone &
browser-hosted applns.
-​ Wpf 4.5 supports various applns development features, such as
control, graphics, layout & data binding.
-​ It has several improvements & enhancements over its previous
version.
1.​ The ribbon control:
-​ Enables u to place some control on a horizontal bar called “ribbon”,
which is present at the top edge of an appln window using this
control, u can create tabs that contain related control.
-​ For ex, MS word, the main tabs on ribbon are Home, Insert, Page
Layout, View etc,.
2.​ Support for validating data synchronously & asynchronously:
-​ By implementing INotifyDataErrorInfo interface.
-​ U can specify user defined validation rules for data entity classes.
-​ This interface also allows u to implement user –defined objects and
custom error objects
-​ It provides support for validating cross property error, multiple
error for single property
3.​ Support for binding to types that implementation ICustomType
provider:
-​ By implementing ICustomType provider interface.
-​ Used to bind an object or custom type with the properties at run
time.
4.​ Support for Fetching binding Info:
-​ Some new API have been added to help u fetch data binding info.

DESCRIPTION API
The target object BindingExpressionBase.Target

The target property BindingExpressionBase.TargetProperty

The source object BindingExpression.ResolvedSource

The source property BindingExpression.ResolvedSourcePrope


rtyName

Whether BindingExpressionBase.BindingGroup
the BindingExpression b
elongs to
a BindingGroup

The owner of Owner


a BindingGroup

5.​ Data binding to static properties:


-​ Enables u to establish data binding using static properties of a
class.
-​ An event can then be defined that is raised whenever the value of
the static property changes.
-​ A static property is shared by each instance of class and can be
used as the source of data binding
-​ For example, if the class SomeClass defines a static property
called MyProperty, SomeClass can define a static event that is
raised when the value of MyProperty changes. U can declare static
event by using any one of the following syntax
public static event EventHandler MyPropertyChanged;
-​ public static event
EventHandler<PropertyChangedEventArgs>
StaticPropertyChanged;
-​ Note that in the first case, the class exposes a static event
named PropertyNameChanged that passes EventArgs to the event
handler. In the second case, the class exposes a static event
named StaticPropertyChanged that
passes PropertyChangedEventArgs to the event handler. A class
that implements the static property can choose to raise
property-change notifications using either method.

6.​ Support for accessing collections on a Non – UI Thread:


-​ In previous version of wpf, a data collection cannot be accessed
from a non-UI thread.
-​ In wpf ‘4.5’, u can use a non-UI thread to access & modify a data
collection.
-​ ∴ A non-UI thread can be used in the background to process the
data collection received from a data source.
-​ The use of non-UI thread in the background, makes the UI thread
more responsive & improves its performance.

7.​ Support for Automatically updating a source of a data binding:


-​ U can prevent a data source in a data binding from frequently
updating its content by using delay property(postpone for a
specified amt of time).
-​ This is done to prevent the source from updating the property
values until the target finishes its task of modifying the values.
-​ For eg : while resizing an image in a image editing application, you
need to save only final size of image.

8.​ New VirtualizingPanel Features:


-​ New properties, such as scroll unit, cache length & cache legth unit
have been added to Virtualizing Panel. This makes the performance
better.
-​ This makes the performance of virtualizingpanel even better

9.​ Support for implementing weak reference to an event:


-​ The gc does not free the memory allocated to an event handler
even when its job is over (the memory remains allocated). This
inefficient management & wastage of memory is called memory
leaks.
-​ Wpf provides weak event pattern that are used to prevent such
memory leaks
10. New method defined in dispatcher class:
̵​ The InvokeAsync methods have been added in dispatcher class.
-​ Invoke is synchronous method that accepts an action or function
<TResult> as its parameter & executes a delegate on the thread.
-​ Invoke Async – same as invoke but asynchronously.

11. Support for the use of markup extension for events:


-​ A markup extension assign a value specified within the curly braces
to an attribute.
-​ In WPF 4.5 events can have markup extension.
12. support for rearrangement of data on modification(live
shaping)
-​ WPF 4.5 supports the concept of live shaping of data, which means
rearranging, filtering, sorting or grouping of data when it is
modified.
-​ Live shaping is a real-time rearrangement of data, which is
performed when data is modified.
13. Improved performance when displaying large sets of grouped
data:
-​ When a large no.of UI elements are displayed at the same time,
performance is affected to a great extent because it requires huge
memory & rendering requirements, making u’r appln show &
unresponsive
-​ UI virtualization supported by WPF 4.5 enable u to display only
those visual elements that are required at any point of time; other
elements are processed only when requirement arises.
14. Support for the validation of data context object:
-​ WPF 4.5 provides the support for validating the connection of a
data context object with item container with which it associated.
-​
❖​Understanding WPF 4.5 architecture:
-​ WPF 4.5 is part of .Net framework 4.5, it contains both managed &
unmanaged components. Managed components of WPF 4.5 are
based on CLR.
-​ In addition to managed components, WPF 4.5contains an
unmanaged component called the Media Integration Layer(MIL or
milcore).

Displaying the and managed


and unmanaged components of
WPF 4.5

-​ They use different feature


of CLR such as cross language
integration, type safety and
security, debugging and
exception handling and garbage collection.
-​ WPF 4.5 contains an unmanaged components called the MIL or
milcore
-​ Managed components: Presentation Framework, Presentation Core
Windows Base & CLR.
-​ Unmanaged components: mil core, user 3.2, windows codes,
DirectX & Kernel. (windows codes, user 3.2, DirectX & Kernel are
part of window Vista OS).
1. Presentation Framework:
-​ This component is implemented as presentation Framework. dll
assembly in .Net framework 4.5
-​ This component provides diff classes that u can customize the
appearance & presentation of WPF 4.5 applns (with diff types of
control, layouts & animation in WPF applns).
2. Presentation Core:
-​ Implemented as Presentation Core.dll assembly.
-​ Provides some of the most commonly used types & feature of WPF
4.5.
-​ Classes 7 types offered by this component provides certain
essential functionalities ∍ properties, events, & messages in WPF
4.5.
3. Windows Base:
-​ Implemented as Windows Base.dll
-​ Provides fundamental WPF features ∍ threading, type converters &
dependency properties.
4. MIL or Mil core:
-​ Unmanaged component in WPF 4.5.
-​ Interacts with DirectX & acts as a medium or interface b/w DirectX
& CLR (& managed WPF components).
-​ Allows the display of 2-D & 3-D graphical content in WPF 4.5
applns & also to work with rendering of DirectX for WPF 4.5
applns.
-​ Mil core is able to use DirectX for WPF applns only because it is an
unmanaged component.

❖​Understanding WPF 4.5 class hierarchy:


-​ The managed components of WPF provide several types & classes.
All WPF classes are inherited from system object class.
1)​System.Windows.Threading.DispatcherObject class:
-​ The DispactcherObject class exists in system.window.Threading
Manage threads. By default, WPF applns run with 2 threads – one
for UI & other for rendering.
-​ 1. UI thread – main executing thread that obtain inputs & events.
-​ 2. Rendering thread – executes in the back ground.
-​ Generally, there is only one UI thread for single WPF appln, but u
can define UI elements on more than one thread . this reqs in
complicated processing of WPF applns.
-​ ∴WPF employs Single-Threaded-Apartment(STA) model to make
applns single threaded.
-​ With STA, WPF applns are compatible & interoperable with various
browsers, ∍ IE.
-​ In STA model, there can be multiple UI threads but only one of UI
threads would run at a time.
-​ The UI elements that are created on one UI thread belong to only
that thread & are not available to other UI threads. This
phenomenon is known as thread affinity.
The interaction b/w multiple threads is implemented through a
dispatcher in which its work item are queued & executed based on
their priority.

2)​System.windows.DependencyObject class:
-​ Allows its derived classes to use dependency property. A
dependency property is a CLR property that is backed by
System.Windows.Dependency property class.
-​ The values of dependency properties depend on several factors or
inputs ∍ styles, themes & animations of WPF objects.
-​ Allow u to use expression as property values, bind data,
incorporate animations & appln styles.
3)​System.Windows.Freezable class:
-​ Allows u to work with objects that have editable & read only
states.
-​ Provides support for change notifications objects of freezable class
are called freezable objects
-​ Freezable objects can have 2 states
-​ 1. Frozen (read-only) 2. Unfroze (editable)
-​ by default you will be having – unfrozen
-​ To improve the performance of WPF applns, object are made
read-only to prevent changes in them
-​ Therefore, System resources would not be utilized for change
notification.
-​ Frozen objects can be shared across diff threads.
-​ Freezable object cannot be frozen under following condition:
1. The object contains any data-bound or animated property.
2. The object contain any properties that are set by
dynamic resources.
3.The object contains any other object that cannot be
frozen.
-​ After an object is frozen, it can not be unfreezed. But u can create
editable copies of frozen object by cloning it.

4)​System.Windows.Media.Visual class:
-​ Is the base class to render the elements used in WPF applns
-​ Visual class provides rendering-related functionalities, ∍ clipping,
transformations & bounding box calculations.
-​ Acts as a link b/w the managed WPF components & the
unmanaged mil core components by generating a tree-like
structure
-​ WPF uses retained mode rendering system(i.e complete
composition tree is cached by the mil core component)
-​ When there are changes are in any composition node, only
changes are conveyed. This ensures faster & optimized repainting
of the screen(using painter’s algorithm).
5)​System.Windows.UI Element class:
-​ Provided APIs to implement the fundamental feature in WPF 4.5
appln, for ex, layouts & events for WPF elements.
-​ UI element Introduces easy-to-use & flexible layout model.
-​ Layout model comprises 2 phases 1. Measure &2. Arrange
-​ 1. Measure phase – determined size of UI element in WPF appln.
The size of element can be determined multiple times, depending
size & position of other elements.
-​ 2. Arrange phase – optimum positon of an element is de ted.
-​ Provides dynamic layouts for the elements.
NOTE: visual & UI Element classes are provided by the
presentation core assembly.
6)​System.Windows.FrameworkElement class:
-​ Is an interface b/w UI Element class & WPF frame-work level
implementation elements. (elements that u use directly in XAML or
code – behind files).
-​ Offers additions features to enhance WPF applns
-​ Help u to uniformly & flexible appln layout & styles to WPF
frame-work level visual elements.
-​ Provides support for specifying diff visual elements in the form of a
tree, animation & story boarding, data binding & event.
7)​System.Windows.Controls.Control class:
-​ WPF has several pre-define UI elements known as control. WPF
Control are derived from this class.
-​ For ex, label, button, radio button & group box control are derived
from control class.
-​ This class provides several properties to add back ground & fore
ground, visual effects, borders & styles, font on the control.
-​ Also provides control template for the same class(define
appearance & behaviour of respective controls)
8)​System.Windows.Control.Panel class:
-​ All the controls have to be enclosed in a panel.(container to hold
other controls)
-​ Adjust the layout & dimensions of controls some panel that inherit
panel class are Grid, Canvas, Stack Panel.
-​ Use a particular panel based on u’r requirements.(Grid – to arrange
the child controls in the form of grid)
-​ (stack panel – to pos child controls horizontally or vertically in a st
line)
9)​System.Windows.Shapes.Shape class:
-​ WPF 4.5 offers extensive support for 2 D-graphics
-​ Is the frequently used graphics elements.
-​ Has several derived classes ∍ Ellipes, line, rectangle & polygon.
-​ Filling shapes with diff colors, adding borders etc.

10 System.Windows.ControlsElement class
-​ Offers some of the core-level functionalities to work with the
content of WPF applns.
-​ Responsible for style & presentation of content.
-​ Offers features to indicate various change in flow content.
-​ Provides methods, properties & events to work with animation &
textual content.

❖​Types of WPF applns:


1. Standalone WPF applns.
2. XAML browser applns (XBAP).
3. User control library.
4. Custom control library.
1. Standalone WPF applns:
-​ similar to windows forms applns.
-​ Allows the use of windows class & WPF dialog boxes ∍ Message
Box, Open File Dialog etc.
-​ Developed to host content & data in rich graphics form & allow
user to interact with data
-​ To create WPF applns:
1.​ start→programs→MS visual studio 2012
2.​ new project→File→New→Project
3.​ installed→Templates→Visual C#→windows(option from left pane)
4.​ select WPF appln template from middle pane opens the designer
interface of standalone WPF appln(similar to windows forms appln)
-​ Initial files required to create standalone applns:
1. Files for standalone WPF application
open solution explorer→click show All Files Button
-​ Under reference node, u can View to essential .Net namespaces &
assemblies ∍ presentation core presentation framework & window
base
-​ If u expand App. Xaml node, u can view the respective
code-behind file, App. Xaml. Cs
-​ App.xaml&App.xaml.cs-collectively represent WPF appln
-​ App.xaml- Is an xaml file – specify required XML namespaces &
resources.
-​ App.xaml.cs-Code-behind C# file
-​ <Application x:class =”WPFApplication1.app”
Xmlns=
http://schemas.microsoft.com/winfx/2006/xaml/presentation”
Xmlns:x= http://schemas.microsoft.com/winfx/2006/xaml”
startupURI=”MainWindow.xaml”>
<Application Resources>
</Application Resources>
</Application>
-​ Main Window. Xaml & main windows. Xaml.cs - corresponds to
default window of WPF 4.5 appln.
-​ <window x:class =”WPFApplication1.mainwindow”
Xmlns=
http://schemas.microsoft.com/winfx/2006/xaml/presentation”
Xmlns:x= http://schemas.microsoft.com/winfx/2006/xaml”
Title=”MainWindow” height=”300” width=”500”>
<Grid>
</Grid>
</window>
2. XBAPs(XAML Browser Application)
-​ XBAPs pronounced as x-baps
-​ XBAPs are web-server hosted WPF appln that run in a web
browser.
-​ XBAPs consists of several pages, which can be accessed &
navigated through a browser
-​ This is similar to working of traditional web sites. Unlikely,
standalone WPF, XBAPs are not installed on user’s computer.
-​ If user’s are offline they can not access XBAP. XBAPs are accessed
from browsers.
-​ XBAPs have limited privileges, while standalone WPF appln run
with privileges of currently logged-in desktop user.

-​ To create XBAPs:
1. start→programs→MS visual studio 2012
2. new project→File→New→Project
3.installed→Templates→Visual C#→windows(option from left
pane)
4. select WPF browser appln template from middle pane to
create XBAP.
-​ you can see the UI of XBAP is similar to standalone WPF appln.
-​ XBAP has some essential files:
-​ App. Xaml, App. Cs are available in XABP. XABPs have page1. Xaml
& page1. Xaml. Cs instead of Main Windows. Xaml & Main Window.
Xaml. Cs page1. Xaml & page1. Xaml. Cs correspond to a page in
XBAP.

-​ Page class – similar to a web page in website, a WPF page is a


basic entity in XBAP. The pages hold the content that is displayed
to users. When u create XBAP, a page is automatically included in it
. when XBAP runs, users can navigate to any page in XBAP.
-​ Hierarchy of page class-
UIelement→Frameworkelement→controls.Page

3. User control library:


-​ Allows u to create user control by using existing control & combine
them into a single reusable unit
-​ They are useful to declare several UI elements & use them
together.
-​ A user control includes a XAML & a code behind file
-​ They are derived from user control class & do not support styles or
templates.
-​ Ex, of user control – login control with 2 labels 2 textboxes & 2
button for OK & cancel.
4. Custom control library:
-​ Used to develop custom controls when existing WPF controls are
not able to serve u’r requirement
-​ They allow u to create controls with the required behaviour &
appearance.
-​ These controls extend or override the UI & behaviour of existing
controls
-​ This include a code file & default style in Themes/Generic. Xaml,
support style & themes. Control class is the base class for WPF
custom controls.
-​ Ex, of WPF custom control : A numeric Up Down control that is an
extension of Text Box control.

❖​WPF 4.5 designer interface:

-​ WPF 4.5 Designer interface Offer an easy, quick & interactive way
of working with. UI or WPF applns.
-​ WPF designer consist of a window, which is a form like structure &
appears at the centre.
-​ Have solution explorer, properties widow & tool box.
-​ Designer interface Divided into 2 primary design views –1. design
2. XAML.
-​ Other designer element ∍ split view bar & the collapse pane, assist
in working with design & XAML views.

1. Design view:
-​ Is the area where u build the visual aspect or UI of a WPF appln by
placing, dragging & resizing and manipulating the appearance of
control.
-​ Design view has several UI element that assist u in quickly
designing WPF appln.
-​ Grid Rails, Grid Lines & Grid Indicators:
-​ Pertain to Grid element or control of WPF. When u create a WPF
appln, Grid element is added by default.
-​ Grid – allows u to rep the WPF appln as a grid or lattice
-​ Entire grid is enclosed by gird rail that span horizontally & vertically
on the top & lf, respectively.
-​ By default gird has one row & one column(there can be multiple
rows & columns also, can be created by clicking the designed
possible on grid rails).
-​ When u click on gird rails, gird lines & gird line indicators appear
accordingly. If u click the gird rail on top, then vertical gird line
appears divided the gird into 2 columns.
-​ Similarly, if u click the grid rail on the left, then a horizontal gird
line appear dividing the gird into 2 rows.
-​ Grid rail can be clicked many times to create multiple rows &
columns.
-​ height & width of the rows & columns can be controlled by moving
the gird line indicators that appear as triangles on gird rails.
-​ Zoom control:
-​ Allows u to zoom in & zoom out the design view. Zoom in upto
12.5% & zoom out upto 800%.
-​ Move & resize handles:
-​ Appear only when u select the control.
-​ Click & drag the move handle to reposition the control.
-​ Margin Lines & Margin Stubs:
-​ In WPF 4.5 control exist within container controls Gird control
automatically added to WPF appln when controls are dragged &
dropped, u can change the dist b/w control & gird known as
Margin.
-​ Margin is measured from edge of the control to nearest gird line.
Each control has 4 margin – top, bottom, left & right.
-​ Margin lines appear only when the control is selected margin
stub(small circle) – indicate that the margin is automatically set for
that edge.
-​ Margins for a control are collectively accessed through margin
property of control.

-​ Snap lines:
-​ Is used to assist u in aligning the controls in WPF applns – appears
only when there is more than one control & u want to align the
control.(press ALT key if do not want to see the snap line)

2. The XAML view:


-​ Allows u to view & work with XAML code for WPF appln.
-​ XAML view & design view are inter-related ∍ whatever changes
make in design view reflects in XAML view & vice versa(i.e, we can
also design WPF appln by using XAML view)

-​ Split view bar:


-​ U can simultaneously work with design view as well as XAML view
(possible because of this)
-​ Has 2 tabs that correspond to 2 panes on its left & 3 button on its
right. (1st tab corresponds to design pane, 2nd tab corresponds to
XAML view)
-​ There is a button, swap panes, b/w the design & XAML panes on
split view bar.(to swap design & XAML view)
-​ There are 3 button on right side of split view bar
-​ 1st button, vertical split - vertically split XAML view & design view.
-​ 2nd button, horizontal split – horizontally split XAML view & design
view.
-​ The 3rd button, collapse pane – allows u to collapse or hide one of
the panes.(if u want to expand the collapse pane, click expand
pane button)

-​ Solution explorer:
-​ Allows u to view projs, refs, & files that are created for a WPF
appln in hierarchical manner.
-​ Use soln explorer to rename, remove & create the projs & files.
-​ Properties window:
-​ Allows u to view & work with the properties of controls.

SOLUTION EXPLORER

Tool box:
-​ Offers several controls that u can use to design UI or WPF applns
drop them on design view.
-​ The control in tool box of WPF designer have 3 tabs
1.​ Common WPF controls – common control ∍ button, check box,
combobox data gird.
2.​ All WPF controls – contains all WPF controls, ∍ canvas, content
control, doc viewer & data picker.
3.​ General – contains any custom controls that u create are placed
under this tab.
-​ Document outline window:
-​ Presents a hierarchical view of UI of current WPF appln
-​ use it select, remove & navigate through UI elements of WPF
appln – not visible by default.
-​ U can select view→other windows→document outline from menu
bar or press CTRL+ALT+T from keyboard(to view this)
-​ Displays the outline or structure of UI elements of WPF appln in a
top-down hierarchy.

❖​Using XAML in WPF 4.5 applicaton:


-​ One of key ingredients in WPF is its base XAML (pronounced as
zammel)
-​ The support for XAML in WPF allows u to declaratively specify UI or
appearance of WPF appln.
-​ XAML loader facilitates u to work with XAML content in WPF appln
– u can draw a line b/w design or UI & the login or functional of
WPF appln.
-​ XAML is used to define UI of WPF appln. & login is added in
code-behind file.
-​ XAML Intellisense feature allows the debugging & compilation of
XAML content.
-​ XAML elements:
-​ XAML is based on XML & uses XML markup tags, elements &
attributes to define UI of WPF appln.
-​ XAML element directly correspond to various managed WPF
classes, while XAML attributes correspond to properties & events of
classes.
-​ XAML namespace correspond to CLR namespaces.
-​ In WPF, XAML elements are represented as a logical true with
several element nodes. Each element corresponds to a tree node
while the attribute of elements become the properties of the
nodes.
-​ When u add an XAML element within an existing element, it
becomes the child element of existing node.
-​ This kind of hierarchical tree-like content model makes WPF applns
extensible & easy to render.
-​ In XAML file, there is exactly one topmost or root element.
-​ In WPF appln, root element is window element, where as in XBAP,
the root element is page element.
-​ Ex: representing XAML elements as a tree

-​ Window, button & label elements have several attributes. For


instance, window element has xmlns, title, height & wide
attributes. Button & label elements have Name & margin
attributes.
-​ Exploring Namespaces & XAML:
-​ Similar to XML, XAML reqs certain predefined namespaces to allow
u to use the element & attributes.
-​ These namespaces convey about the loc of the classes & structural
rules or schemas of WPF applns to the XAML parser, when u create
WPF applns, refs to the necessary namespaces are added
automatically in the windows element(WPF appln) & page elt(in
XBAPs).
-​ The appln element also contains refs to necessary namespace by
default 2 namespaces are included in WPF appln .
-​ The namespaces are added by using the xmlns declare
​The xmlns declaration of 1st namespace is as follows.
-​ XML namespace=
http://schemas.microsoft.com/winfx/2006/xaml/presentation.
-​ specifies default namespace for XAML file & WPF applns. This
namespace for XAML file as a URI.
-​ Includes all XAML elements & attributes that are require to work
with WPF specifically.
​The xmlns declaration of 2 namespace is as follow
-​ Xmlns: x= “http://schemas.microsoft.com/winfx/2006/xaml”
-​ Specifies the namespace that is required to work with XAML in
general. - This is more exhaustive & provides all essential XAML
elements & attributes.
-​ XAML namespace specifies x: as an alias for the namespace.
-​ The XAML namespace are provided as URIs while the CLR
namespaces are provided as dot-separated names.
-​ XAML & CLR namespaces map or correspond to each other using
XMLNS Definition Attribute – which takes XAML & CLR namespaces
as its args to map them.
Exploring XAML property syntax:

-​ U can set the properties of WPF classes by setting the appropriate


XAML attributes.
-​ The individual attributes are separated by whitespaces & are
specified in name-value pairs.(name=value).
-​ Ex: <button height= “23” name= “button1”> welcome
</button>.
-​ Setting the properties through XAML attributes is easy, concise &
intuitive, WPF provides an alternative way, known as property
element syntax.(set the properties by specifying them as elements
rather than as attributes).
- Syntax:
<element-name.property-name [attribute1-name= “value1”
attribute2-name= “value2” – attributeN-name=
“valueN”]>property-value</element-name.property-name>
1. Element-name – specifies the name of the element to which
property belongs.
2. Property-name – specifies the name of the element to which
property.
3. Attribute1-name, - attributeN-name – specify name of any
attributes that the property may contain.
4. Value1,.....valueN – specify the values of attributes.
5. Property-value – specify the value of property
- In the above syntax , property name is qualified with element
name to which it belong by using dot operator.
- Ex: <button>
<button. Height>25</button. Height>
<button. Name>button1</button.name>
<button. Content>welcome</button.Content>
</button>
●​ Exploring markup extensions:
-​ Till now, WPF properties are set by using direct & explicit values.
-​ In some cases, u may want the properties to set to a ref to a
particular object(using markup extensions).
-​ A markup extension is a means of setting the value of a property
to an object ref (allows u to delay the assignment until runtime).
-​ Markup extensions provide an easier, flexible & efficient way of
assigning values to properties through attributes & property
element syntax
-​ Markup extension assist u to set the property to different type of
values.
-​ The markup extension classes inherit
system.Windows.Markup.Markup Extension Class.
-​ Markupextension classes – 1. BindingBase 2.
TemplateBindingExtension, 3.StaticResourceExtension 4.
DynamicResourceExtension 5.ArrayExt 6. NullExt 7.TypeExt
●​ Adding rows & columns to a grid through XAML:
-​ The grid element(control) is by default added to standalone WPF
applns & XBAPs
-​ The grid element by default has only one cell, i.e, one row & one
column.
-​ Adding more rows in grid – vertically increases cells.
-​ Similarly to increase no.of cells horizontally, add more columns.
-​ Note that the changes made in XAML view is immediately reflected
in design view & vice versa.
❖​Exploring WPF properties:
-​ WPF framework provides a set of properties that can be used to
extend the functionality of CLR properties.
-​ Properties hold great significance in WPF, as they are easy-to-use
& easy-to-validate.
-​ WPF includes the following properties.
a.​ Dependency.
b.​ Attached.
a. Dependency properties:
-​ Dependency Object & Dependency Property. Classes play a key
role in the WPF property system.
-​ The WPF property system allows u to extend the existing CLR
properties by backing them as dependency properties.
-​ Dependency properties refer to those properties that depend on
various factors or inputs ∍ data binding, animations, resources &
styles to determine their values.
-​ They support many of the complex & advanced functionalities.
-​ Dependency properties can be categorized as,
1.​ Read-only – cannot be modified – useful in cases where u want the
value of dependency property to be set only once (used when u
want its value to be influenced by only one inputs).
2.​ Collection-type: which has a value of collection type. All
dependency properties are instances of the Dependency Property
class. This class contains many properties & methods that assist u
in implementing & working with dependency properties in WPF.
​Properties of dependency Property Class—1. Default Metadata, 2.
Global Index(index that uniquely Identifies a dependency
property),3. Name,
4. Owner Type,5. Property Type, 6. Read Only.
​Methods—1. Add Owner 2.Get Metadata, 3. Is Valid Type, 4. Is
Valid Value, 5. Register, 6. Register Attached, 7. ToString etc.
-​ U can use dependency properties in XAML through property
element syntax, as
-​ <button Height= “25”, width= “150” Name= “button1”, back
ground= “orange”> Dependency property
</button>
-​ U can also set these properties in code-behind file
Button button1= new Button( );
Button1. Height=25;
Button1. Width=150;
Button1. Back ground= brushes.orange;
​Precedence of dependency property values:
-​ (highest to lowest) – affected by various factors/inputs.
-​ INPUTS—1. Property Coercion, 2. Animations,3. Loca lValues,
4. TemplatedParentElement, 5. Styles, 6.StyleTriggers
7. Template Triggers 8. Style Setters, 9. Theme Styles,
10. Inherited Values, 11. Value from Metadata.
-​ Property Value Inheritance:
-​ The elements in WPF applns are, treated as nodes in a hierarchical
tree with one element nested inside another.
-​ In most cases properties of an element are available to its child
elements also.
-​ For that u need to enable property values inheritance that refers to
the process where an element inherits the value of a dependency
property registered on its parent element.

-​ Dependency property validation & coercion call backs:


-​ WPF also offers validation call backs that validate the value of the
dependency properties.
-​ The value of the dependency property is changed
programmatically: & the property metadata is overridden.
-​ Validation call backs: 1. Are suitable to check whether a particular
value is within a particular range.
2. are methods that take single object as their arguments & return
a boolen value.
-​ Syntax: Public static type Validation Call Backs Method(Object
Value)
{
//validation login
}
-​ Public, static, and object – represents c# keywords
Type – represents the type of dependency properties
Validation Call Backs Method – represents the name of the
validation callback method that is passed as an argument to the
Validation Call Backs delegates
Value – represents the value that is to be valid
-​ U can also coerce the values of the dependency properties to a
particular value or a range of values through the coercion
callbacks.
-​ Some times the value of a dependency property changes
depending on the modifications done in some other properties, so
use a property change call back along with coercion call back.
-​ Syntax: Private static object coerce Call Back
Method(Dependency Object dobj, Object Values owner of
dependency property {
//coercion login
}
-​ Private, static, object, Dependency Object, - represents c#
keywords
coercion Call Back Method - represents the name of the coercion
callback method that is passed as an argument to the corec Call
Backs delegates
dObject – owner of dependency property
value – value that validated
-​ Syntax : property changed call back
Private void static property Changed Method(Dependency Object
dobj, Dependency Property Changed Event Args e)
{
//property changed login
}
-​ Private, static, object, Dependency Object and Dependency
Property Changed Event Args , - represents c# keywords
Property changed Method - represents the name of the method
that is passed as an argument to the Property changedcallback
delegates
dObject – owner of dependency property
-​ Dependency Property Metadata:
-​ Every dependency property has a metadata that refers to an object
containing a lot of info about, the dependency property.
-​ Include default value, the ref to coerce & property changed call
backs.
-​ Useful when u want to change the value of an existing dependency
property without re-implementing the dependency property or
creating new one.
-​ U can change/override the metadata of a dependency property in
the derived classes of the owner of dependency property.
-​ Implemented through the Property Metadata class – has a derived
class – UI Property Metadata.
-​ Which itself is inherited by Framework Property Metadata class. –
is mainly used to work with property metadata for dependency
properties.
​Properties of Framework Property Metadata: 1.Affects Arrange,
2.Affects Measure,3. Affects Render, 4. Default Value, 5. Inherits,
6. Is Sealed etc.
-​ Custom Dependency Properties:
-​ WPF has a gamut(range) of dependency properties that is exposed
through diff WPF classes.
-​ U may need to create u’r own dependency properties, known as
custom-dependency properties.
-​ U can implement, any kind of WPF functionality to create custom
dependency properties .(animations, styles & data binding).
-​ NOTE: u can create a dependency property only for a class, that
directly or indirectly inherits the Dependency Object class. The
dependency property is then instantiated to create dependency
property identifier.(needs to be registered by using register
method). After registering the dependency property, it is wrapped
with a CLR property that users Get Value ( ) & Set Value( ) public
methods.
2. Attached Properties: refers to dependency property that can
access & set to any of child objects or elements.
-​ Help the child elements to provide info about their appearance &
presentation to parent element.
-​ Implied as dependency properties in the parent.
-​ U can also create user-defined attached properties.(needs to
inherit dependency object class).
-​ A field of dependency property type is declared to create attached
property, which is then registered using Register Attached( )
method.
-​
-​ Exploring WPF events:
-​ WPF has significant changes or improvements in the domain of
events & event handling.
-​ Incorporates an enhanced event system.
-​ Event system offers 2 new concepts 1. Routed events, 2. Attached
events.
-​ Each events has its own lifetime(stages – created, loaded &
destroyed)
1.​ Routed events:
-​ WPF appln has numerous elements. These elements are
represented in the form of a tree with one root element.
-​ Expect root, all other elements can have more than one nested
elements.
-​ Most of these elements have certain basic events(mouse/key board
events).
-​ These events are defined as routed events in WPF.
-​ Routed events route or traverse through the element tree of WPF
appln.
-​ Differ from traditional CLR events because routed events allow u to
raise & handle an event on multiple elements.
-​ Originates at one element but can traverse either up/down the
element tree from source element – is raised on elements b/w the
root element & the source element & can be handled on each of
those elements.
-​ Routed events belong to WPF event system & are backed by
Routed Event Class.
-​ Properties of Routed Event class:
1. Name, 2. Handler Type, 3. Owner Type, 4. Routing Strategy.

-​ Routing Strategy – is a way in which an event is raised & traversed


in b/w the elements of elements tree.
-​ Specified with the help of the values of Routing Strategy
enumeration. The values are
A.​Direct events.
B.​Tunnelling events.
C.​Bubbling events.
A. Direct events: Directly appln on elements on which they
originated or raised.
-​ Similar to CLR events
-​ Can be raised & handled only on the source element & not routed
through other elements in the element tree.
B. Tunnelling events: originate on one element but are raised &
handled on the root/parent elements.
-​ In other words, tunnelling events are raised from the root element
in the tree down to the child element that originally raises the
event, i,e from outer element to inner element.
-​ Tunnelling events are also called preview events, as the names of
the events are prefixed with preview.
-​ Preview Mouse Right Button Up: is associated with its handler,
Mouse Right Handler in all the elements.
-​ This event is a tunnelling routed event that is available to all
elements derived from UI Element class when u right click any
element, this event occurs on the root element & tunnel downs to
source element.

C. Bubbling events: originate on one element but are raised &


handled on all parent elements up to the root element.
-​ Raised from the child element to the root element in the order of
their hierarchy.

-​ Handlers for Routed events:


-​ Routed events traverse through the element tree. They are raised
& handled at the level of each element from source element to
root element & vice versa. There is an entire range of routed
events offered by WPF.(code behind file).
-​ Syntax of event handler:
Public return Type event handler Name(OS, R EA, e)
{
//event handling logic
}
-​ Public, object, routedeventargs – represents c# keyword
-​ Return type – represents the return type of event handler
-​ Event handler – represents the name of the event handler
-​ Sender – represents the recent sender of event

-​ Properties of Routed Event Args Class:


1. Handled, 2.Originate Source, 3.Source, 4. Routed Event
-​ After adding the event handler u need to associate the handler
with appropriate event u can do it by using various event
attrinbutes in XAML file,
-​ <Button Height= “25” Width= “75” Name= “my button” Vertical
Alignment= “center” Click= “my button-click”>Button1
</Button>....
-​ myButton_click() defined in code behind file is specified as event
handler for click event.
-​ Alternatively, u can associate the handler with the routed event in
code-behind file by using += operator.
-​ My Button. Click += new RoutedEventHandler(my Button_Click)

●​ Custom Routed Events:


-​ U need to create custom routed events for custom controls or
elements – involves declaring a static read-only field; registering
the field as a routed event & wrapping the routed event as CLR
event.
-​ Steps:
1. Create a new WPF appln, Frame Routed Event.
2. Add the following code in Main Window. XAML.Cs.

PROGRAM:
Public partial class frame: border
{
//declaring the routed event field.
Public static readonly Routed Event On Mouse Hover
Event;
static frame( )
{
On Mouse Hover Event= Event Manger. Register Routed
Event(“On Mouse Hover”, Routing Strategy. Bubble, type
of(Routed Event Handler), type of(Frame); \\
registering the routed event
}
Public event Routed Event Handler On Mouse Hover
// CLR wrapper for routed event*/
{
Add {
Add Handler(On Mouse Hover Event, Value);
}
Remove {
Remove Handler(On Mouse Hover Event, Value);
} }
Protected override void On Mouse Move(Mouse Event
Args e)
{
Raise Event (new Routed Event Args(Frame. On Mouse
Hover Event));
/* raising routed event*
} }
-​ Use the frame class and associate a handler for On Mouse Hover
event, by adding the following code in main windows class Main
window. XAML. Cs file.
-​ Public void Frame-Mouse Hover(OS, R EA, e)
{
MessageBox.Show(“mouse hover event of frame
handler”);
}
3. Add the following code in Main Window. XAML to use frame
class.
<window x: class= “Frame Routed Event. Main Window”
XMLNs= “http//schemas. microsoft.
com/winfx/2006/xaml/presentation”
Xmlns: x= “http//schemas.microsoft.com/winfx/2006/xaml”
Title=“Main Windows” Height= “312”, Width= “346”
Xmlns: my= “clr-namespace: frame Routed Event”,
<Grid>
<Grid. Row Definitions>
<Row Definition Height= “50*.”/>
<Row Definition Height= “50*”/>
<Grid. Row on Mouse Hover= “Frame-Mouse Hover”, Grid. Row=
“0”>
<button. Name= “button1” height= “25”, width= “75”, content=
“Inside Frame”/>
</my. Frame>
<button Name= “button2” height= “25”, width= “10”, Grid. Row=
“1”, content= outside Frame”/>
</Grid>
</window>
4. Run Frame Routed Event appln (by pressing F5)
OUTPUT:

2. Attached Events: events that are owned/ created in one element


or class – can be handled by any element in the elements tree.
-​ Useful when u want to provide info about the compositing state of
a child element to the parent element.
-​ Parent element can handle an event i.e, defined by a child
element.
-​ If event is raised on any one of them, then the event handler can
be specified only once in parent element.
-​ Handler for an attached event is specified in the parent by
qualifying them with name of owner.
-​ For ex, click is an attached event, owned by Button Base & is
inherited by its derived classes & elements ∍ Button & Toggle
Button Classes.
-​ <Grid Name= “grid1” Button Base. Click= “Button-click”
-​ Attached events are routed events & are registered with Register
Routed Event( ) method. – does not have CLR add and remove
event wrappers.
-​ They use 2 public static method to add & remove the event
handlers.

-​ Syntax: Public static void Add <Attached Event Name> handler( )


{
//add event handler logic
}
​Life time of events:
-​ Event element has its life. Life time of elements is characterized by
particular stages or events.
-​ Common events that characterized life time of elements in WPF
are.
●​ Initialized – refers to very 1st event that occurs in life time of an
element. raised
-​ when an element is created. If an element contains a child
element, then this event occurs 1st on the child element moving up
to the parent element.
-​ Because, parent element is not fully initialized & set, unless its
child elements are initialized.
●​ Loaded: refers to 2nd life time event that occurs after the initialized
event signals that all the elements in the appln are set & ready to
be rendered. - Loaded event 1st occurs at the root element & then
moves down to child elements.
●​ Unloaded: refers to last life time event. This event occurs when a
specific element, or its root or parent element is removed from the
WPF appln.
​Application life time events:
-​ The standalone WPF applns & XBAPs follow a particular seq of
events during their life time. The life time events of standalone
WPF appln are as follows.
●​ Startup – refers to 1st event that occurs just after the run( )
method is called for the appln. The startup event indicates that the
appln is ready to be displayed. In the event handler of the startup
event, u can create a window object & specify it as the main
window for the appln.
●​ Activated – refers to the event that occurs when a standalone WPF
appln becomes the active appln. (when the window of the appln
appears on top)
●​ Deactivated: when an appln is no longer the active appln or
becomes inactive. (window goes in the background & not current
window)
●​ Session Ending: when the appln, shuts down & the current user
terminates the window session. – occurs if user shuts down or
restarts the computer or logs off from session.
●​ Exit: just before the appln shuts down. In Exit event, u can specify
any finalizing actions, such as saving the exit code.
​Window Life time events:
-​ Each window in the appln has a life time, which itself is
characterized by a series of events.
●​ Source Initialized – when the window is initialized. i.e, when the
standalone WPF appln is initialized & its start up event is raised –
This event signals that the window is ready to be displayed.
●​ Activated: when window becomes the active window(i.e, the
window appears in front).
●​ Loaded: when a window & its properties are loaded & window is all
set to be rendered.
●​ Content Rendered: the window & its content(control) is rendered.
If the window does not have any content, then this event may not
occur.
●​ Deactivated: when current window becomes inactive.
●​ Closing – defers to the event that occurs when a user closes the
window.(occurs before the window is closed)
●​ Closed – just before window is closed. This event signals that the
window would close in a while & there is no way to cancel closing
operation.

▪​ Working with Dialog Boxes in WPF appln:


-​ Similar to window forms standalone WPF applns can also make use
of dialog boxes for better user interactivity.
-​ In WPF 4.5, dialog boxes can be of 2 types
1.​ Modal dialog box: remains visible unless explicitly closed. As long
as a modal dialog box is opened, u can not work with any other
window of the appln. suitable to retrieve certain info from the
users & utilize that info for further processing. Ex: dialog boxes for
opening & saving files.
2.​ Modeless dialog box: does not prevent the users from working with
other windows of the appln. it do not affect the functioning of
appln. it is suitable to display info.
̵​ WPF provides various classes to create dialog boxes and use them
in applns.1. messagebox 2. Openfile 3. Savefile 4. printfile
1.​ Message Box Class: allows u to create message boxes
o​ simplest model dialog box
o​ used to display some info that can be used to confirm a particular
action or make decisions.
o​ has Show( ) method to display a message.
o​ by default OK button is displayed. (u can also display other button,
such as cancel, Yes & No).
o​ If u want to convey the user whether the message is a warning or
additional info, the u can display an icon on the message box by
using Message Box Image enumeration.

o​ Steps to create a message box in WPF appln:


1.Create a new WPF appln, Delete Item Confirm.
2. Add the following code in Grid element of Main Window. XAML
file
<button Height= “23” Margin= “92,0,112,41” Name= “Delete
Button” vertical Alignment= “Bottom” Click= “Delete
Button-Click”> Delete</Button>
A button is added to the Grid element
3. Double-click the Delete Button button in design view. The
code-behind file, Main Window. XAML. Cs of Delete Item Confirm
appln appears. Delete Button-Click( ), is the handler for click event
of Delete Button, is included in Main window class of code-behind
file. Add the following code in file,

Message box result my result= MessageBox.Show(Are u sure u


want to delete this Item? ); “Delete Item”, Message Box Button.
Yes No, Message Box Image.
If (my result. To String( )== “Yes”)
Message Box. Show(“item deleted”);

4.run Delete Item Confirm appln & click delete button.


Delete Item message box appears
o/p:

-​ When u click a button in message box, the selected action will be


stored in my result object & its value is checked by using if
statement. No→delete Item. Confirmation box is closed.
Yes→another message box is displayed.

2. The Open File Dialog class: allows the users to provide the name
of 1 or more files that are to be opened. Hierarchy of Open File
Dialog Class is.
System. Object
Microsoft. win32. Common Dialog
Microsoft. win32. File Dialog
Microsoft. win32. Open File Dialog;
(same as Open File Dialog of window from) – has Show Dialog( ) &
Open File( ) method. File Name & Filter properties, File
event.(Open File( ) method in WPF OFD)

3. Save File Dialog Class: allows u to specify the name, locate &
type with which u want to Save Exists, File Name & Initial Directory
properties.
SFD in WPF has 2 additional properties named Safe File Name&
safefilenames
Microsoft. win32. File Dialog
Microsoft. win32. save File Dialog;

4. Print Dialog Class: allows u to specify & configure the printer


̵​ allows u to specify various setting & options related to printing
process.
-​ (similar to Print Dialog Class in windows forms).
-​ There are certain different due to some additional.
-​ Properties & methods in Print Dialog Class of WPF.
o​ Properties – Max Page, Min Page, Page Range, page Range
Selection, Printable Area Height, Printable Area width, Print Queue,
Print Ticket, User Page Range Enabled.
o​ Methods: Print Document, Print Visual(non-textual)

▪​ Compiling & running WPF 4.5 applns:

-​ Compilation of WPF appln involves the compilation of XAML & c#


code in code behind file.
1.​ XAML code is build/compiled using XAML compiler into Binary
Appln Markup Lang(BAML)
-​ BAML also known as binary XAML files.
-​ BAML has .baml extension
-​ Baml embedded into .Net assemblies.
-​ When WPF appln executes, this binary XAML file is used to create
the visual tree that is used to render UI elements in WPF appln.
-​ U can build or compile WPF 4.5 applns in VS 2012 by selecting
BUILD→build solution option from the menu bar.
-​ The XAML compiler creates .baml file & stores it in <WPF
Application>/<WPF Application Project>/obj/x86/Debug folder.
-​ Also creates another file called generated file(.g.cs). For
standalone WPF, there are atleast 2 generated files App. g.cs &
Main window.g.cs similarly App.g cs & Page1.g.cs are generated
for XBAPs.
2.​ After compiling XAML code, the generated files & .Net language
code are compiled by lang compiler(csc.exe) into an assembly.
-The assembly can be an executable (.exe) or .dll &contains the
.baml file as a resource when the compilation of WPF appln is
complete, u can run it.(by selecting Debug→Start or F5).
-​ Working with WPF 4.5 Controls, Resource, Styles, Templates &
Commands
-​ WPF is a technology used for building attractive GUIs for
standalone & browser applns.
-​ Used .XAML-based lang, to create & manage diff UI elements ∍ .
window, images, videos.

▪​ Adding WPF control:

-​ WPF has rich set of controls(some are similar to windows forms


controls but differ in their look & behaviour).
-​ As u change the XAML code of a control, the look of WPF control is
automatically changed in Design View.
-​

-​ U can controls to a WPF appln either


1.adding control Through an XAML code,
2. adding control Through a code-behind file or
3. By dragging & dropping controls from tool box on a WPF
window.
1.​ Adding control through an XAML code:
-​ Create a WPF appln & add the code Main Window.XAML file
<window x:class= “Adding Controls-XAML. Main window”
Xmlns=
http://schemas.microsoft.com/winfx/2006/xaml/presentation
Xmlns:x= “http://schemas.microsoft.com/winfx/2006/xaml
Title= “Main Window” Height= “300” Width= “300”>
<Grid>
<Grid. Row Definitions>
<Row Definitions Height= “53”/>
​ <Row Definitions Height= “53”/>
​ <Roe Definitions Height= “76”/>
​ <Row Definitions Height= “81”/>
</Grid. Row Definitions>
<Grid. Columns Definitions>
<Columns Definitions Width= “141”/>
<Columns Definitions Width= “137”/>
</Grid. Column Definitions>
<Label Fontsize= “15” Margin= “26, 12, 43, 10”>
Login ID:
</Label>
<Text Box Horizontal Alignment= “Right” Margin= “0, 12, 12, 8”
Name= “Login” Width= “116” Grid. Column= “1”/>
<Label Font size= “15” Grid. Row= “1” Margin= “26, 10, 17, 11”>
Password:
</Label>
<TextBox Grid. Row= “1” Horizontal Alignment= “Right” Margin=
“0, 9, 12, 12” Name= “password” Width= “116” Gird. Column=
“1”> </Text Box>
<Button Margin= “12, 17, 18, 22” Name= “submit” Grid.
Row=”2”>
Submit
</Button>
<ButtonGrid. Row= “2” Margin= “9, 17, 26, 22” Name= “clear”
Grid. Column= “1”> clear </Button>
</Grid>
</window>
2.​ Adding controls through a code-behind file:
-​ Create a WPF appln & replace Grid element with the code.below.
<Grid Name= “my grid”>
</Grid>
-​ Open MainWindow.xaml.cs file & add the code
Public partial class Main Window: window
{
Public Main Window( )
{
Initialized components( );
​ Label my label= new label( );
​ My label. Content= “Enter u’r Name”;
​ My label. Font size= 12;
​ My label. Font weight= Font Weight. Bold;
​ My Grid. Children. Add(my Label);
Text Box T1= new Text Box( );
T1. Margin= new Thickness(0, 5, 10, 5);
T1. Height= 30;
T1. Width=150;
My Grid. Children. Add(T1);
T1. Horizontal Alignment= Horizontal Alignment. Right;
T1. Vertical Alignment= vertical Alignment. Top;
Button b1= new Button( );
B1. Content= “submit”;
B1. Font size= 11;
B1. Font Weight= Font Weighs. Bold
B1. Height= 50;
B1. Width= 75;
My Grid. Children. Add(b1);
}
}
Press F5.

​ Diff types of controls in WPF :

-​ WPF offers several controls ∍ Grid, Text Box & Rich Text Box.
-​ The working of controls in WPF depends on 2 base classes: control
& Frame work Element.
-​ The control class is a public base class derived from Frame Wrok
Element class
-​ Each control in WPF is classified under one of the following types.
1.​ Container controls.
2.​ Simple controls.
3.​ Content controls.
4.​ Headered content controls.
5.​ Item control controls.
6.​ Headered Item controls.
7.​ Miscellaneous controls.
1.​ The container controls:
-​ These controls provide built-in layout functionalities for child
controls
-​ handle the layout & positioning of child controls.
-​ It includes Grid, Uniform Grid, canvas, Dock panel, stock panel,
wrap panel.
̵​ Grid control: most commonly used
-​ window automatically includes a Grid control by default.
-​ consists of a single cell. U can add additional rows & columns
inside Grid control
-​ child elements are arranged on columns & rows. – can contain
another Grid control as child element.
-​ Grid is derived from panel class
<Grid>
</...child elements....>
</Grid>
o​ Properties of Grid class
Columns Definitions, Row Definitions, Show Grid Lines
o​ Attached properties of Grid class (in XAML refer to global
properties that can be set on any object)
Attached properties: Columns, Columns Span, Is Shared Size
Scope, Row, Row Span
o​ Hierarchy – system.object
System.windows.threading.dispatcherobject
System.windows.DependencyObject
System.windows.Media.Visual
System.windows.UIElement
System.windows.FrameworkElement
System.windows.controls.panel
System.windows.controls.grid

2. Uniform Grid controls: Arranges the content in the Grid


control in such a way that the cell in the grid remain the same size
̵​ control are arranged in a grid patten
​̵ adjusts to accommodate diff controls
​̵ derived from panel class
o​ u can add <Uniform Grid>
//
</Uniform Grid>
o​ Properties – columns, First Column, Rows
o​ Hierarchy- panel→ primitives.uniformgrid
3. Canvas control: simplest container control that supports
absolute positioning of its child controls(by using co-ords)
- must specify one horizontal property & one vertical property to
denote starting pos of child control inside canvas control
- this only container that has no built-in layout of its own.
- By default height & width are set to zero.
o​ Attached properties: Bottom, Left, Right, Top(margins)
o​ u can add <canvas>
//
</canvas>
o​ hierarchy - panel →canvas
4.Dock panel control: container where a no.of related child
elements can be placed either vertically or horizontally.
- Position of child elements can be det.ed by using Dock Panel.
Dock dependency property, which can be set to Top, left, right or
bottom to pos the child elements.
- By default, child elements are of same size. U can change the
size by using height & width attributes.
- Derived from panel class.
- the 1st child element u add in Dock Panel Control takes up all the
space on Dock Panel Control.
o​ Property - last child fill – specifies a value that indicates whether
the last child control within Dock Panel control will stretch to fill
remaining available space.
o​ Attached property - Dock – indicate the pos of a child control
within parent Dock Panel control
o​ U can add <Dockpanel>
//
</Dockpanel>
Hierarchy - panel →dockpanel
5. Stack Panel Control: position child elements as if they were
on a stack & arranges them into single line that can be oriented
either vertically/horizontally.
- By default – vertical
- can be changed by using orientation property – arranges the
stretched to full wide)
o​ Hierarchy -- panel → stack panel
o​ Properties of Stack Panel - Can Horizontally Scroll, can Vertically
Scroll, Extent Height, Extent Width, Orientation etc.
6. Wrap Panel control: position its child elements in a sequential
order.(order depends on value of orientation property)
- default is horizontal.(arrange from left to right).
Vertical – top to bottom.
o​ Hierarchy-- panel →wrappanel
o​ Properties of Wrap Panel -Item Height, Item Width, Orientation
2. Simple controls: do not contain any child elements within them
added by simple dragging them from tool box or by writing XAML
code in Main Window. XAML file.
1. Text Box control: display or edit unformatted text
̵​ perform a spell check by setting SpellCheck.IsEnabled to true.(false
by default)
̵​ has a context menu(by default).
​̵ single multi lines
​̵ Textbox control has a context menu
​̵ Context menu allow user to perform cut copy paste
​̵ text wrapping, Accepts Return property(allows user to insert a new
line by pressing Enter key).
̵​ Set Vertical Scroll Bar Visibility & Horizontal Scroll Bar
Visibility(adds scroll bar when text in control reaches the end of the
frame)
o​ Derived from Text Box Base class.
o​ Properties – Character Casing, Line Count, Max Lines, Selected
Text, Selecting Length, Selection Start, Text
o​ Hierarchy- controls.control →primitives.textboxbase →textbox
2. Rich Text Box control: similar to Text Box control
- ideal when user needs to edit formatted text, images or tables
- provides additional functions ∍ displaying font, colors & links.
- supports basic editing commands. – derived from Text Box Base.
o​ Properties – Document, Selection, Is Document Enabled.
o​ Hierarchy - controls.control →primitives.textboxbase →richtextbox
3. Password Box control: special text box control designed to
enter & handle passwords
- hides the text entered in it.
- ensure privacy.
- The most important diff b/w a Text box & password box control
is that it uses System. Security. Secure String object, which
ensures that the text entered as a password in password box
control is kept confidential
- The text is encrypted for privacy when it is in use, & deleted
from memory. When no longer required. To over write password.
Secure string. Dispose( ) is used.
o​ Properties – Max Length, Password, Password Char.
o​ hierarchy controls.control →primitives.textboxbase →password box
4.Scroll Bar control: provides a scroll bar that has a sliding
Thumb control.
- This control contains a track control, which in turn contains a
Thumb control & 2 repeat button controls.
- U can increase/decrease the value property of scroll bar control
by moving the thumb control or by clicking repeat button controls.
- The default range of value property is from 0to 1.
- This can be changed by setting. Maximum & Minimum
properties, which are provided by Range Base class.
o​ Derives from Range Base class, which in turn derives from control
class.
-​ Displayed horizontally/vertically by orientation of scroll bar.
o​ Properties: Orientation, Track, View Port Size.
o​ Hierarchy- controls.control →primitives.Rangebase
→permitivescrollbar
5. Progress Bar control: indicates the progress of an operator.
- It consists of a bar that shows the % of operator completed in
the form of filled cover
- this control is not user interactive.
o​ Derived from Range Base
o​ Properties: Is indeterminate, Orientation.
6. Slider control: allows a user to select a value from a range of
values by moving Thumb control. Ex: volume control in a media
player.
- slider control is Interactive control
o​ Hierarchy of slider class: control→Range Base→Slider.
o​ Properties: Auto Tool Tip Placement – tool tip containing the
current value of a control is displaced at the time of pressing
Thumb control, Delay, Maximize Value, Minimize Value, Orientation
etc.
3. Content controls: displayed to contain a single nested element
- help u to add content to control. Ex: Button, Label, Check Box,
List Box etc.. 1. Button: similar to one used in windows from.
̵​ Basic UI element that raises Click event.
̵​ Can insert text/images,
o​ Hierarchy - Control→content control→Button Base→Button
o​ Properties – Is Cancel, Is Default, Is Defaulted
2. label: can contain text or other controls in it.
- Allow u to add/display text in design view.
- In WPF it also provides support for access keys.
o​ Hierarchy- control→content control→label
o​ property: target→specifies/retrieves a control that receives the
focus when a user presses access key of label control.
3. Radio Button control: used to select an option from a given
list of options.
- Radio Button can be selected but not cleared, u can clear Radio
Button. - - - When u select another radio button control(Mutually
excusive)
o​ hierarchy - control→content control→Button Base→Toggle
Button→Radio Button
o​ property: Group Name
4. Check Box: represents the option that a user can select/or
clear
- single/multiple controls
o​ hierarchy - hierarchy - control→content control→Button
Base→Toggle Button→Radio Button.
5. List Box Item control: represents a selectable item in List Box
control
- set Is Selected property to true to select an item
- can set horizontal/vertical alignment.
o​ Hierarchy - Control→content control→List Box Item
o​ Properties – Is Selected
6. Status Bar Item: reps an item of status bar control
- items & Item source properties of status bar control are used to
add content to status bar item control.
- This control can not be added from Tool Bar
- has to be added through XAML code.
o​ Hierarchy - Control→content control→primitives.statusbaritem
7. Scroll viewer control: reps a scrollable area that can contain
other visible elements
- provides a convenient way to enable scrolling of content in WPF
appln when content in UI is larger than a display area
- 2 types of scrolling –1. physical & 2. logical.
1. Physical – used to scroll contents by physical increment
typically by value default.
2. Logical – used to scroll to next item in logical true of elements.
o​ Properties – computed Horizontal Scroll Bar Visibility, Computed
vertical scroll bar visibility, Extent Height, Scrollable Height,
Horizontal Scroll Bar Visibility,
Extent Width, Scrollable Width, Vertical Scroll Bar Visibility.
o​ Hierarchy - Control→content control→ScrollViewer
8. Tool Tip control: small pop-up window, which appears when a
user hovers/place the mouse points over an element.
- If the user moves the mouse points away, then the Tool tip
disappears.
- The content of this control can be text, images, shapes or visual
content,
- cannot have a parent control(i.e, u can not add a tool tip control
inside another control).
- Tool tip cannot be added from Tool Box – added through XAML
code
o​ Properties: Custom Popup Placement Call Back, Has Drop Shadow,
Is Open, Placement, Placement Rectangle, Placement Target, Stays
Open.
o​ Hierarchy - Control→content control→ToolTip
9. Content control: used to display content & has some
pre-defined styles
- u cannot change the appearance of control
- can enhance by creating new Data Template class.
o​ Properties – content, content template, Has content.
o​ Hierarchy - Control→content control
10.Window control: helps in creating, configuring, showing &
managing the life time of a window or dialog box
- consists of 2 areas.
1.Client area- hosts appln specific content
2.Non-client are - hosts common controls ∍ minimize, maximize,
window control is added to WPF appln by default
- This control is a root element & can not be a part of content of
another element.
- Window control appears by default along with Grid control in WPF
appln.(u cannot drag & drop, added by default)
o​ Properties – Allows Transparency, Dialog Result, Is Active, Left,
Owner, Resize Mode, Title Top, Top most, window state, Window
Style
o​ Hierarchy - Control→content control→window
11.Frame control: supports content navigation & display.
- can be hosted in other content as well as controls
- u can navigate to a web page by using navigate()method. The
life cycle of navigation can be tracked through Navigating,
Navigated, Navigation Progress, Navigation Failed, Navigation
Stopped, Load completed & Fragment Navigation events.
o​ Properties of Frame: Back Stack, can Go Back, Forward Stack,
Navigation Service, Navigation UI Visibility etc.
o​ Hierarchy - Control→content control→Frame
12. Navigation window control: derived from window
- designed to support content navigation. U can navigate by
setting the source property of Navigation Window control with URI
of desired content.
- u can track the events raised during navigation.
- Cannot be added from Tool box(added through XAML code).
o​ Properties: Back Stack, Can Go Back, Can Go Forward, Forwad
Stack, Navigation Service etc.
o​ Hierarchy - Control→content control→window→navigationwindow
13. User-control control : provides an empty control which
create custom control
- helps in creating controls which can be used in multiple places
with in an appln.
o​ Properties: Active Control, Anchor, Causes Validation, Has Children
etc.
o​ Hierarchy - Control→content control→usercontrol
4. Headered content control: are the controls that contain the
Header & content properties.
̵​ Header property consists of a text value, whereas content property
consists of a single content item.
-​ Inherit the content property from content control & define Header
property, which is used to provide haeding for control.
1. Expander – represents a control that display a header with a
collapsible window
̵​ U can set the content area of expander control to expand in one of
4 directs: Down, Up, Left, Right by using Expand Direction
properties.
̵​ When the content area of Expander control collapses, only header
& its toggle button are visible.
o​ Hierarchy =Control→content control→Headered content
control→Expander
o​ Properties – Expander Direction, Is Expanded
2. Group Box: provides a titled container with a border & a
header, for graphical UI content.
- Header property – header
- U can add multiple controls inside
o​ Content property – content
o​ Hierarchy =Control→content control→Headered content
control→groupbox
3. Tab Item: contained with Tab control class, - header can be
added by using Header property. The Tab control reps the
selectable item inside Tab control. (can contain multiple Tab Item
control).
o​ Only one item is visible
o​ Properties – Is Selected, Tab Strip Placement(dets how a Tab Item
control is placed on a window)
o​ Hierarchy =Control→content control→Headered content
control→TabItem
5. The Items Control controls: display a collection of items & do
not have the content or Header property. – controls are grouped as
collection of Items.
1. Context Menu: represents a popup menu that enables a
control of the functionality that is specific to the content of the
control
- displayed by right clicking the mouse
̵​ represented by Context Menu class which is derived from abstract
base class, Menu Base. Each context menu control is specific to the
control it is attached to.
̵​ It is diff from other Items control controls as it is contained within
another control & creates a menu in the form of a pop-up.
̵​ cannot from be added from the Tool box – added through XAML
code.
o​ Hierarchy control→Item control→primitive. Menu Base→context
Menu
o​ properties: Is Open, Placement, Placement Rectangle, Placement
Target, Stays Open
2. Data Grid control: used to display the required data in the
right format from any data source ∍ a dataset, data base table &
xml file.
̵​ It generated the columns automatically, on the basis of the Item
source property, u can also perform operators ∍ grouping, sorting
& filtering
̵​ can perform validation on the cell & row levels.
o​ Hierarchy-
control→Itemscontrol→primitives.selector→primitives.Multiselector
→DataGrid
o​ Properties: Auto Generate Columns, Can User Add Rows, can-user
Delete Rows, Selected Cells.
3. Status Bar control: displays item & info in a horizontal bar
and used to display text & image indicate.
̵​ U can divide the items in status bar control by using separator
control.
̵​ Events are raised when a user clicks the item in Status Bar control.
o​ Hierarchy -control→Item control→primitive. Status Bar
o​ property: Separator Style Key
4. menu control: represented by Menu class
̵​ derived from Menu Base.
̵​ represent a windows menu to hierarchically organize the elements
associated with commands & event handlers
̵​ presents a list of item that specify commands/options for an
appln.
̵​ The content properties of Menu control are set by using the Items
& Item source properties to generate the content of item controls.
o​ Hierarchy - control→Item control→primitives. Menu Base→Menu
o​ property: Is Main Menu
5. list Box control: displays the items from a list
̵​ all items are visible by default.
̵​ To make only selected item visible u need to set Is Drop Down
property to true.
̵​ u can select more than one item at a time from List Box control by
setting the Selection Mode property to single multiple or Extended.
o​ Properties – Selected Items, Selection Mode.
o​ Hierarchy - control→Item control→primitives.Selector→ListBox
6. Combo Box: similar to list box
- displays a list of items
̵​ has additional Button control to display an item only if control is
clicked.
̵​ This list is displayed/hidden as Button expands/collapses
̵​ default –collapsed & shows only one item.
o​ Properties: Is Drop Down Open, Is Editable, Is Read Only, Is
Selection Box Highlighted, Max Drop Down Height, Text.
o​ Hierarchy - control→Item control→primitives.Selector→ComboBox
7. List view: provides the infrastructure to display a set of data
iten in diff layout/views.
​̵ u can display items in the tab format & sort them by using List
View control.
o​ Property: view
o​ Hierarchy - control→Item
control→primitives.Selector→ListBox→ListItem

8.Tree view: used to display item in a hierarchical manner.


̵​ contains a hierarchy of Tree View Item control.
​̵ u can expand/collapse by setting Is Expanded to true/false when a
user selected the Tree View Item control, the selected events is
raised & Is selected property is set to True.
̵​ When a user deselects the Tree View Item control, unselected
event is raised & Is selected property is set to false.
-​ Default view of tree view control places the control inside a
stackpanel container control.
o​ Properties-SelectedItem, SelectedValue, SelectedValuePath
o​ Hierarchy -control→Item control→Tree view
9. Tab control: Helps in arranging content in the tabular form
̵​ consists of multiple Tab Item control that share same screen space,
only one Tab Item control is visible at a time.
̵​ When a user selects the Tab Item control the content of control
becomes visible (other hidden).
o​ Properties: selected content, Tab Strip Placement(dets alignment of
tab headers)
o​ Hierarchy - control→Item control→primitives.Selector→Tabcontrol
10. Ribbon control: enables u to place some controls on a
horizontal bar called Ribbon, which is present at the top of WPF
appln window – makes it easier to access & run frequently
executed commands. - u can create tabs that contain related
controls.
Can be added from Tool Box or by writing XAML code.
o​ Properties: Border Thickness, Clip, Allow Drop(indicates whether
the element can be used as a target in a drag & drop operator),
Font Size, Font Style.
o​ Hierarchy - control→Item
control→primitives.Selector→Ribbob.ribbon

6. Headered Item controls: To display main, parent-level controls,


or objects along with their child control.
1.Tree View Item control: help in displaying info in a
hierarchical struct by using collapsible nodes. The content
properties if Tree View Item control are Item & Item Source,
Header property is Header. U can expand/collapse a Tree View
Item by Is Expanded property
can not be added from Tool box – added through XAML code
o​ Hierarchy - control→Item Control→Headered Items control→Tree
View Item
o​ properties: Is Expanded, Is Selected

2. Menu Item control: represents the selectable menu item


contained in Menu control. The menu classes Menu & context
Menu, include the item of Menu Item control.
The Menu Item control can have submenus, which are made up of
objects within Item collection of Menu Item control.
o​ Can not be added from Tool box – added through XAML code.
o​ Properties Menu Item class: command(retrieves the command
associated with Menu Item control), Command parameter,
Command Target, Icon, Input Gesture Text open t, Is Checkable, Is
Checked, Is Highlighted, Is Submenu Open, Role, Stays Open On
click, Submenu Item Template Key, Top Level Item Template Key.
o​ Hierarchy - control→Item Control→Headered Items control→
MenuItem
3. Tool Bar control: is a container for a group of control. – place
a Tool Bar inside Tool Bar Tray control, which arranges Tool Bar
control according to available space – usually contains button to
invoke commands.
o​ Properties: Band(specifies a value that indicates where a Tool Bar
should located in Tool Bar Tray control Band Index( - indicates the
pos of a Tool Bar control on Band property control), Button style
Key, Check Box Style Key, Combo Box Style Key, Has Overflow
Items, Is Overflow Open, Menu Style Key, Orientation, Radio
Button Style Key etc.
o​ Hierarchy - control→Item Control→Headered Items
control→ToolBar

7. Miscellaneous. Controls: provide added functionalities to WPF


appln.
1. Border control: responsible for drawing a border back ground
or both around a control. – can have only one child element(i.e, at
a time, that Border control can apply a border or background to
only single element. U can display multiple child elements with
Border control by adding the Panel element within the Border
control.
o​ Hierarchy- System. Windows. Framework Element
System. Windows. Control. Decorator
System. Windows. Control. Border
o​ Properties: Corner Radius, Border Thickness.
2. Text Block control: provides flexible text support for appls. –
used with documents in WPF. – presentation of text – text can be
added bu Text property.
o​ Hierarchy- System. Windows. Framework Element
System. Windows. Controls. Text Block
o​ Properties: Break After, Break Before, Content End, Content Start,
Font Family, Font Style, Foreground, Padding, Text, Text Alignment,
Text Decorations, Text Effects, Is Hyphenation Enabled, Text
Trimming, Text Wrapping.
o​ Note: label & Text Block are similar only diff is Text Block can
display large amount of text.
3. View box control: represents a content decorator that can
stretch & scale a single child element to fill the available space in
View box control of a WPF appln. – can have only one child
element.
̵​ adding more than one child throw an Argument Exception.
o​ Hierarchy - Framework →Decorator→View box
o​ Properties – child, Stretch, Strech Direction
4. Access Text control: represents an underscore that is used as
an access key.(ex: CTRL+C, C is access key).
- If u’r text has multiple underscores, then only 1st one is
converted into access key.
- Add the control through XAML code.
o​ Hierarchy -Framework Element→Control→AccessText
o​ Properties: Access Key, Baseline Offset(specifies a value that
adjusts the baseline offset position), Font family, Font Size, Font
Size, Font Weight, Text, Text Alignment, Text Decorations, Text
Effects, Text trimming, Text Wrapping
5. Grid Splitter control: responsible for redistributing the space
b/w rows & columns of Grid control.(without changing the dims of
the control)
o​ Hierarchy- Framework Element→Control.
control→Controls.Primitive. Thumb→controls. Grid Splitter
o​ Properties: Drag Increment, Key board Increment, Preview Style,
Resize Behaviour, Resize Direction, Shows Preview.
6. Virtualizing Stack Panel control: (data binding can be
applied container controls) used this control when u r binding
items to Stack Panel control & there is not enough space to display
all the item.
o​ this arrange the content on a single line, horizontally/vertically. If
the items are not data bound then there is no advance. Hierarchy-
Framework Element→controls Panel→controls.Virtualizing
Panel→controls. Virtualizing Stack Panel
o​ Properties: Can Horizontally Scroll, Extent Height, Scroll Owner
Can Vertically Scroll, Extent Width
7. Calendar control: allows u to select a data as well as fire an
event on select of data. U can display the selected date.
- u can customize calendar control with Style property.
o​ Hierarchy- Framework Element→controls. control→controls.
Calendar
o​ Properties: Blackout Dates(u do not want a user to select), Display
Date, Display Date End, Display Date Start, Display Mode, Is Today
Highlighted, Selected Date, Selected Dates, Selection
Mode(indicates whether a user can select a date, range of dates or
multiple range of dates).
8. Date Picker control: allows a user to select a date,
- Selected Date Changed event is fired implicitly. A user can select
a date by entering in text box of Date Picker control or by clicking
associated calendar. - U can display unabbreviated days of the
week & names of the months, limit the range of date displayed in
the attached calendar.
o​ Hierarchy - control→Date Picker
o​ properties: Blackout Dates, Calendar Style, Display Date, Display
Date End, Display Date Start, Is Drop Down Open, Is Today
Highlighted, Selected Date, Selected Dates, Selected Date Form.

●​ Using WPF controls:

-​ User can add a WPF control to a WPF appln by dragging the


control from Tool box or adding XAML code in Main Window. XAML
file. – using WPF control designers can design more attractive &
interactive GUIs for both windows & wed-based applns.
-​
●​ Setting absolute position of controls:
-​ Canvas control defines an area where u can position the child
elements. U can also add canvas to an WPF appln through XAML
code.
<window x: class= “canvas Control. Main Window”
Xmlns=
http://schemas.microsoft.com/wifx/2006/xaml/presentation
Xmlns: x= “http://schemas.microsoft.com/winfx/2006/xaml”
Title= “Main Window” Height= “328” Width= “422”,
<canvas Background= “#FFE2E2D9”>
<Button canvas. Left= “88” canvas. Top= “117” Height= “23”
Name= “my button” Width= “75”>
Hello!</Button>
<Label canvas. Left= “69” canvas. Top= “50” Height= “28”
Name= “my label” Width= “120”> Ex of canvas
</Label>
</canvas>
</window>

●​ Adding Border to controls:


-​ Add border/background/both to a control.
-​ Here we add a border to grid.
-​ Window, xmlns, xmlns:x, Title – same as above
<Grid>
<Border Background= “pink” Border Brush= “Black” Border
Thickness= “5” corner Radius= “30”/>
<Button Border Brush= “Blue” Height= “100” Width= “100”
Border Thickness= “4” Background= “Blue Violet”/>
</Grid>

●​ Using password control: special kind of Text box – display Text


entered by a user in encrypted form.
<Grid>
<Border Background= “Peach Puff” Corner Radius= “25”/>
<Label Height= “28” Horizontal Alignment= “Left” Margin=
“10,10,0,0” Name= “label” Vertical Alignment= “Top” Width=
“120”> Enter u’r name </Label>
<Label Height= “28” Horizontal Alignment= “Left” Margin=
“10,48,0,0” Name= “Label2” Vertical Alignment= “Top” width=
“120”>Enter password </label>
<Text Box Height= “23” Horizontal Alignment= “Right” Margin=
“0,12,14,0” Name= “text box1 Vertical= “Top” Width= “120”/>
<Password Box Horizontal Alignment= “Right Margin= “0, 53,
14,0” Name= “password box1” Width= “120” Height= “23” Vertical
Alignment= “Top” Max Length= “10” Password Char= “*”/>
<Button Height= “23” Margin= “84, 0, 119, 103” Name=
“Button1” Vertical Alignment= “Bottom”>submit </Button>

●​ Creating a scrollable Area in a WPF window:


-​ Using scroll Viewer control(where u’r content is more than the size
of the window).
-​ Create vertical scrolling area by setting the Vertical Scroll Bar
Visibility property & a horizontal scrolling area by setting
Horizontal Scroll Bar Visibility.
<Scroll Viewer Horizontal Scroll Bar Visibility= “Auto” Vertical Scroll
Bar Visibility= “Auto”>
<Rectangle width= “400” Height= “400” Fill= “Red”>
</Scroll Viewer>

●​ Using the Slider control: to select a value from a range of values. –


mainly used in media players. U can display the position of tick
marks on the slider control by using Tick Placement
property(sound)
●​ Using View box control: is a content decorator that can stretch &
scale a single child control to fill the available space in the View
box control.
<View box>
<canvas Height= “400” Width= “500” Background= “Blanched
Almond”>
<Ellipse Height= “300” Width= “400” Fill= “Red” Canvas.
Right= “100” Canvas. Left= “60”>
</Ellipse>
</Canvas>
</View box>

●​ Using Expander control: used to provide content in an expandable


area
<Grid>
<Expander Width= “200” Horizontal Content Alignment=
“Center”>
<Expander. Header> Click on the arrow
<expander. Content>
<Scroll Viewer Height= “45”>
<Text Block Text Wrapping= “Wrap with Over Flow>
This is an ex of expander control. This is also using Scroll Viewer
control. U can use both the controls together to give u’r appln a
good look & feel
</Text block>
</Scroll Viewer>
</Expander. Content>
</Expander>
</Grid>

●​ Using Navigation Window & Frame controls:


-​ U can navigate to a web page by using Frame & Navigation
Window controls. U can add a Frame control to a WPF appln &
call web page in Frame control. This is possible by adding
Navigation Window control to WPF appln, which renders the web
page in WPF appln.
-​
●​ Using the calendar & Date Picker controls
-​ Calendar and Date Picker:
<Grid>
<Calendar Height= “170” Horizontal Alignment= “Left” Margin=
“12,65,0,0” Name= “ Calendar1” Vertical Alignment= “Top” Width=
“180” Selection Mode= “Multiple Range”>
<Calendar. Blackout Dates>
<Calendar Date Range Start= “2|1|2011”End “2|6|2011>
</Calendar. Blackout Dates>
</Calendar>
<Date Picker Height= “25” Horizontal Alignment= “Left” Margin=
“216,65,0,0” Name= “date picker1” Vertical Alignment= “Top”
Width= “200” First Day Of Week= “Monday” Selected Date
Format= “Long”>
<Label content= “calendar” Height= “28” Horizontal Alignment=
“Left” Margin= “73,12,>

▪​ Exploring Resources:

●​ allow u to reuse commonly defined objects & values in an appln. –


mainly used to apply same style to more than one window control
(u need define a resource in the main appln file & the style will
be applied to all controls present in WPF appln)
̵​ resources can be categorized as 1. static & 2. dynamic. U can refer
a resource by using markup extension, which is feature of XAML .
-​ Resource provide an enhanced way of managing properties of
controls in WPF appln.
-​ Any resource that is defined for a control also applied for all its
child elements.
-​ U can define a resource for a single control or globally on a page
that can be used by all the controls on the page.
●​ Understanding Static Resource: are those that do not intend to
change after they are referenced the 1st time – always loaded on
creation of a window. U can refer by using Static Resource markup
extension.
-​ U should define the resource dictionary in u’r appln before u refer
the static resource. Static resources are not assessed at runtime
& using them during runtime will throw an exception.
-​ Static resource follow a lookup process for their implement.
-​ 1. Check for required key with in the resource dictionary key is
defined by the element that sets the static resource
-​ 2. The process then moves to the logical tree upwards to the
parent element.
-​ 3. Then to its resource dictionary.
●​ Understanding dynamic resource: that can be changed after they
are referenced for 1st time
-​ is applied by using Dynamic Resource markup extension→create
on expression →the expression remains unchecked until appln is
actually run.
-​ The value of dynamic resource depends on the condition that are
not known until runtime – they are referred for a custom control.
-​ U need to adjust the content of Resource Dictionary class during
an appln lifetime.
-​ The lookup process for a dynamic resources checks for the
required key.
-​ The key is located winthin the resource dictionary that sets the
property of element.
-​ The lookup process then tracks the logical tree to the parent
element & its resource dictionary. This process continues until
root element is reached.
-​ Accessing resource from code: Resource can be defined & used in
.XAML files in WPF appln.
-​ Add a resource to Main Window. Xaml, access the resource
through Main Window. Xaml. Cs.

▪​ Exploring Style & Templates:

-​ U can use resources to store a wide variety of objects. A style can


be defined as a collection of properties that can be applied to an
element. U can define a set of styles for controls & apply them to
appln. A WPF style can set any Dependency property & use is to
apply non-formatting characteristics(∍ behaviour of a control)
WPF styles also use templates to define appearance of control.
●​ Styles in WPF 4.5:
-​ Styles allow u to apply a set of properties to more than one
element. U can change the style of the Text Block control by
changing its Font Size &Font Family properties.
-​ U can bind a style to a control by using style property. Styles set
the initial appearance of an element. U can Override the
characteristics u set in a style. Styles have some advances over
resources.
-​ A style allow u to create groups of related settings. It also
streamlines u’r markup by making it easier to apply these setting.
-​ Hierarchy: System. object→System. Windows. Threading.
Dispatcher Object→System. Windows. Style.
-​ U can add the style class to a WPF appln.
●​ Properties of style class:
-​ Setters, triggers(used to apply property values according to
specified conds). Resources(collection of resources used with
style). Based On(specifies a defined style that is used with current
style), Target Type.
-​ A style is most commonly declared as a resource. Style declare.
Consists of style object that contains a collection of 1 or more
setter objects. Each setter object consists of the property & value
properties.
●​ Setting styles through resource:
-​ Resource are helpful in setting styles in WPF because resource
enable the styles to be reused in appln. If delare the style in the
root element of an appln, then the style can be used in that
appln. If u declare the sytle in one of the applns XAML files, then
the style can be used in that XAML file only.
●​ Extending an existing style: If u want 2 controls to share the same
style, create a new style that is based on 1st style.
●​ Handling Events in styles using Event Setter class:
-​ Used to represent an event setter in a style.
-​ They raise the specified event handlers in response to routed
events.

●​ Templates used in WPF :


-​ Allow u to customize the appearance of controls. – derived from
Framework Template base class. – 2 types of templates in WPF.
i.​ Control Template – responsible for specifying visual structure of
control.
ii.​ Data Template – responsible for specifying graphical represent of
objects.
i.​ Control Template:
-​ Allows u to specify the visual structure & behaviour of a control
that can be shared among multiple instances of controls. –
defined the appearance of control.
-​ Add control Template to WPF appln
<control Template>
<!- - Visual Tree>
</control Template>
-​ Properties: Target Type, Triggers
ii.​ Data Template: all about presentation of data – specify
visualization of data objects. – describes how a data object should
be displayed. There are 2 types of controls that support data
Templates a. Content controls b. List control.
-​ Data Template is useful when u’r binding Item controls ∍ List Box.
Control, to an entire collection.
●​ Template Binding:
-​ Helps a template to retrieve a value from the control to which the
template is being applied.
-​ Similar to data binding & allows developers to bind values with
templates – supports only one-way binding & can not be used to
draw info from the property of a class that derives from Freezable
class
●​ Understanding Triggers:
-​ Trigger class defines the kind of style that u want to apply to u’r
controls. They are set conditionally(for ex, u can change the
background color of a button when u move the mouse over it).
Trigger can also inherit properties through derived styles with
Based On property. Trigger are linked to styles through Style.
Trigger collection. Every style can have unlimited number of
triggers. Each trigger derives from System. Windows. Trigger
Base namespace.
-​ U can also apply trigger directly to elements, without the need of
creating a style, by using Framework Element Triggers
collection(only supports event triggers)
-​ Diff types of Triggers used in WPF are:
o​ Property Trigger.
o​ Event Trigger.
o​ Multiple Trigger.
o​ Data Trigger.
1. Property Trigger: reacts when a property value changes. U
can attach actions to a property Trigger in 2 ways. 1. Use Trigger.
Enter Actions property to set the action that are performed when
the property changes to the values u specify. 2. Use Trigger. Exit
Actions property to set the actions that are preformed when the
property changes back ti its original value.
-​ U can easily change the appearance of controls in WPF by using
this trigger. U can assign a trigger by using Is Mouse Over or Is
Keyboard Focused property.
2. Event Trigger: property Trigger waits for a property change
to occur, while Event Trigger waits for a specific event to be fired.
-​ Event Trigger requires a series of actions that modify the control
with which it is attached. These actions are used to apply an
animation. – specifically starts a set of actions based on the
occurrence of an event(u need to select events that do not
interfere with the inherent behaviour of a control)
3. Multiple Trigger: allows u to set property values based on
multiple conditions. – use when the property of a control is
data-bound. When the value of a property of a control matches
the specified value, u can apply changes/start action by using
Enter Actions or Exit Actions property.
-​ Trigger Base→Multi Trigger
-​ Code:
<Multi Trigger>
<!- - setters - ->
</Multi Trigger>
4. Data Trigger: allow u to set the property values when the
bound data matches a specified condition – similar to Multi
Trigger(only diff = property value has to be matches with a specific
condition) – u need to specify both binding & Value properties on a
Data Trigger.
-​ Trigger Base→Data Trigger
-​ Code:
<Data Trigger>
<!- - setters- ->
</Date Trigger>
●​ Actions & Triggers:
-​ Data trigger is used to change a property in an appln on the values
of peroperty.

▪​ Exploring WPF commands:

-​ A command is an input mechanism in WPF that provides a way for


handling input data (ex – cut, copy, paste) command – separates
action from its logic
-​ Commands are very useful when diff appln have diff controls, but
require same functionality. – aloe users to reuse the same
functionality across multiple applns. – based on Routed command
& Routed Event classes.
-​ Simplest way to use command is to use per-defined Routed
command class from command library classes.
-​ Before using WPF commands, they must be defined with input
Gestures to invoke the commands
-​ (input Gestures are similar to short cuts ∍ F2, to run an appln)
-​ WPF commands can be created by 3 steps.
1.​ Defining the command sources
2.​ Defining the command target
3.​ Binding a command to an appln logic
1. Command sources:
-​ Triggers a command(ex: button/Menu Item – source)
-​ Implements I Command Source Interface
-​ Properties: Command, Command Target, Command Parameter
WPF classes that implement. I Command Source are Button Base,
Menu Item& /hyper Link – invoke command when they are clicked.
-​ Can Execute Changed: event informs the command source about
the ability to execute a command. Command Source queries the
current status of Routed command class by using Can Execute( )
method.
2. Command Target: is an element on which the command target.
If command target is not defined, current control is used for
command target.
3. Command Binding: links command to related appln logic –
represented by Command Binding class. – which contains
Command property & events ∍ Pre View Executed, Execute, Pre
View Can Execute. Command Binding class is implement because
single command might be used in Several place in an appln

●​ WPF commands with controls:


-​ In WPF users can use pre-defined routed commands ∍ Application
Command. Pre-defined commands can be used with controls that
have native support for handling & invoking the commands ∍ Text
box & Menu Item.

You might also like