C# - WINDOWS PRESENTATION FRAMEWORK
C# - WINDOWS PRESENTATION FRAMEWORK
UNIT -2
INTRODUCTION TO WINDOWS PROGRAMMING
▪ 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( );
}
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.
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;
}
- 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>
DESCRIPTION API
The target object BindingExpressionBase.Target
Whether BindingExpressionBase.BindingGroup
the BindingExpression b
elongs to
a BindingGroup
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.
- 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.
- 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)
- 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.
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. 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;
- 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
▪ Exploring Resources: