wpf window

24
1

Upload: mindtree-campus

Post on 11-Mar-2016

246 views

Category:

Documents


2 download

DESCRIPTION

WPF Windows

TRANSCRIPT

Page 1: WPF Window

1

Page 2: WPF Window

2

Page 3: WPF Window

What is a window

Windows are the basic elements in any desktop application. It is a rectangular area that allows th user to interact with the standalone application or desktop application.

It basically gets divided into two distinct sections:

1) The client area is the surface inside the window boundaries. It hosts application-specific content like elements of the form such menu bars, toolbars, buttons textboxes , list boxes or status bars etc.

2) The non client area includes the border and the title bar at the top of the window. It also includes other window

elements like System menu, minimize button, maximize button, restore button and close button.

The implementation of a typical window includes both appearance and behavior. The appearance defines how a window looks to users. The behavior defines the way a window functions as users interact with it. The appearance and behavior of a window can be implemented using either code or XAML markup.

3

Page 4: WPF Window

Anatomy of WPF Window

A WPF window is a rectangular that implements the look and its behavior.

Typically a WPF Windows is divided into two distinct sections

1) Client Area

2) Non Client Area.

What is the structure of Client Area?

The client area of a window is the area within a window's non-client area. This area includes application-specific content, such as menu bars, tool bars, and controls like list box, status bars buttons, textboxes.

Example a Student Registration Form would typically include input text controls like textboxes to provide name, address, city, contact, email and List box with appropriate list of educational degrees to provide information about qualification and so on.

What is the structure of Non Client Area?

The non-client area defines the parts of a window that are common to most windows like

1) A border for the windows

2) A title bar that displays the tile of the window.

3)An icon – A standard image as a n icon in the extreme left of the window bar.

4) Standard Window Buttons like

a)Minimize button that would help minimize a running window,

b)Maximize, button that would help to maximize the window and

c) Close button that shuts down the running window.

A WPF window is an instance on Windows class that derives from ContentControl class of WPF’s core managed API library.

In the next slide we will discuss about WPF Windows class.

4

Page 5: WPF Window

Working with MessageBox Dialog

Consider the code snippet below,

MessageBoxResult dr = MessageBox.Show("Do you want to close this window.....", "Dialog test", MessageBoxButton.YesNo, MessageBoxImage.Question);

if (dr == MessageBoxResult.Yes)

{

this.Close();

}

The code snippet displays the MessageBox with the Message(‘Do you want to close the window’) , Title (DialogTest) and the Buttons – Yes, No and the Image –Question tag. as shown on the presentation.

The code above also shows how to check whether the user has clicked ‘Yes’ button. The line this.Close() closes the currently executing parent window, on which the MessageBox is displayed.

5

Page 6: WPF Window

The OpenFileDialog and SaveFileDialog classes acquire some additional features). Both support a filter string, which sets the allowed file extensions. The OpenFileDialog also provides properties that let you validate the user’s selection (CheckFileExists) and allow multiple files to be selected (Multiselect). The example on the the presenatationshow how to open a filedialog that fileter all image files like *.jpg, *.GIF, *. BMP and alos helps listing other files. The property CheckFileExist properties validates the user’s selection (CheckFileExists) and MultiSelect allow the user to select multiple files.

6

Page 7: WPF Window

This window holds a Grid with three rows, which are used for the title bar, the footer bar, and all the content in between. The content row holds a second Grid, which sets a different background and holds currently, it holds just a single TextBlock.

7

Page 8: WPF Window

The above example uses a StackPanel layout with the a background property as image using ImageBrush. It also includes another property opacity that is set to 0.7 . The WPF window includes a transparent button and a opaque button. The image of the StackPanel is visible through first Button as it is transparent.

8

Page 9: WPF Window

In WPF, a window is encapsulated by the Window class that you use to do the following:

Display a window.

Configure the size, position, and appearance of a window.

Host application-specific content.

Manage the lifetime of a window.

Window encapsulates the ability to create, configure, show, and manage the lifetime of both windows and dialog boxes, and provides the following key services:

A Window can be implemented using markup, markup and code-behind, or code.

Example:<Window x:Class="LayoutDemos.HelloWindow"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Title="HelloWindow" Height="300" Width="300" Background="AliceBlue">

<StackPanel>

<Button Height="23" Name="btnHello" Background="BurlyWood" Foreground="BlueViolet" Width="75" Click="btnHello_Click">Click Me..!</Button></StackPanel>

</Window>

using System;

using System.Collections.Generic;

using System.Windows;

using System.Windows.Controls;

namespace LayoutDemos

{

public partial class HelloWindow : Window

{

public HelloWindow()

{InitializeComponent();}

private void btnHello_Click(object sender, RoutedEventArgs e)

{MessageBox.Show("Welcome to WPF...");}

}

}

Windows Class Method and Events:

Windows class methods:

OnActivated: Raises the Activated event of window.

OnClosed: Raises the Closed event.

OnClosing: Raises the Closing event.

OnDeactivated: Raises the Deactivated event.

OnRender: When overridden in a derived class, participates in rendering operations that are directed by the layout system. The rendering instructions for this element are not used directly when this method is invoked, and are instead preserved for later asynchronous use by layout and drawing.

Show: Opens a window and returns without waiting for the newly opened window to close.

Windows class events:

Activated:Occurs when a window becomes the foreground window.

Closed:Occurs when the window is about to close.

Closing:Occurs directly after Close is called, and can be handled to cancel window closure.

ContentRendered:Occurs after a window's content has been rendered.

Deactivated:Occurs when a window becomes a background window.

Loaded:Occurs when the element is laid out, rendered, and ready for interaction.

Unloaded:Occurs when the element is removed from within an element tree of loaded elements.

Windows class properties :

AllowsTransparency: Gets or sets a value that indicates whether a window's client area supports transparency. This is a dependency property.

Background: Gets or sets a brush that describes the background of a control. This is a dependency property.

ContextMenu: Gets or sets the context menu element that should appear whenever the context menu is requested through user interface (UI) from within this element. This is a dependency property.

DataContext: Gets or sets the data context for an element when it participates in data binding. This is a dependency property.

DialogResult: Gets or sets the dialog result value, which is the value that is returned from the ShowDialog method.

IsActive: Gets a value that indicates whether the window is active. This is a dependency property.

MaxHeight: Gets or sets the maximum height constraint of the element. This is a dependency property.

MaxWidth: Gets or sets the maximum width constraint of the element. This is a dependency property.

Opacity: Gets or sets the opacity factor applied to the entire UIElement when it is rendered in the user interface (UI). This is a dependency property.

Parent: Gets the logical parent element of this element.

Style: Gets or sets the style used by this element when it is rendered. This is a dependency property.

Title: Gets or sets a window's title. This is a dependency property.

WindowStyle: Gets or sets a window's border style. This is a dependency property.

ShowDialog:Opens a window and returns only when the newly opened window is closed.

Example : Display windows by using Show()

EmployeeWindow winEmp = new EmployeeWindow ();

winEmp .ShowDialog();

To display a window, create an instance of the Window class and use the Show() or ShowDialog() method. The ShowDialog() method shows a modal window. In addition, the ShowDialog() method doesn’t return until the modal window is closed, so any code that you’ve placed after the ShowDialog() call is put on hold.

(Note : What is Modal window?

In any windows application, Modal windows stop the user from accessing the parent window by blocking any mouse or keyboard input to it, until the modal window is closed.) Modal windows are ideal for presenting the user with a choice that needs to be made before an operation can continue. For example, consider Microsoft Word, which shows its Options and Print windows modally, forcing you to make a decision before continuing.

Show () Method:

The Show() method shows a modeless window, which doesn’t block the user from accessing any other window. The Show() method also returns immediately after the window is shown, so subsequent code statements are executed right away. Example : Microsoft Word’s Spell check window

payRollMainWindow winMain = new payRollMainWindow();

winMain.Show();

To close a window, use the Close() method. Alternatively, a window can be hidden from view using Hide() or by setting the Visibility property to Hidden.

WPF allows a window to “own” other windows. Such windows are useful for floating toolbox and command windows. For instance, the Find and Replace window in Microsoft Word. Owned windows are always shown modeless windows. To support opening other window, the Window class support a property called owner, that decides the owner window. Example,

// Create a new window.

CustomWindow custWin= new CustomWindow ();

// Designate the current window as the owner.

custWin.Owner = this;

// Show the owned window.

custWin.Show();

Modal Windows as Dialog Windows:

DialogWindow dialog = new DialogWindow();

if (dialog.ShowDialog() == true)

{// Some user action code goes here

}else{

// The code for the canceled action.}

Common Dialog Boxes

The Windows operating system includes many built-in dialog boxes that you can access through the Windows API. WPF provides wrappers for just a few of these. For Example , MessageBox of System.Windows.MessageBox class that displays a standard windows MessageBox by calling Show () method.Example MessageBox.Show(“Do you really want to Delete.", “Delete Message", MessageBoxButton.YesNO, MessageBoxImage.Question) ;

9

Page 10: WPF Window

WPF InteroperabilityWPF and Windows Forms present two different architectures for creating application interfaces. But WPF allows to use Win forms controls in WPF and vice-versa. The key classes that facilitate interoperability are WindowsFormsHost and ElementHost from the System.Windows.Forms.Integration namespace

Windows Presentation Foundation, especially in its first release, lacks some features that previous technologiesalready have. When creating a WPF-based user interface, you might want to exploit such features. For example, WPF currently doesn’t include some of the standard controls that Windows Forms already has: DateTimePicker,MonthCalendar, NumericUpDown, MaskedTextBox, NotifyIcon, DataGridView, and more. Windows Forms alsohas support for multiple document interface (MDI) window management. Win Forms do not supports features like 3-D graphics, animations Typography effect , document services etc.WPF controls that make use of such features can be designed . Then such WPF controls can be used in C# Winforms to take advantage of WPF features that otherwise C# Win forms lack.

Few scenarios for WPF interoperability where Windows Presentation Foundation-based Application Host Windows Forms Controls :

•The WPF control may host one or more Windows Forms controls using XAML.•It may host one or more Windows Forms controls using code.•It may host Windows Forms container controls that contain other Windows Forms controls like Masked Edit or MonthCalendarcontrol.•It may host a master/detail form with a WPF master and Windows Forms details.•It may host a master/detail form with a Windows Forms master and WPF details.•It may host one or more ActiveX controls.•It may host one or more composite controlsFew scenarios for WPF interoperability where Windows Forms-based Application Hosts Windows Presentation Foundation Controls•Hosting one or more WPF controls using code.•Hosting one or more WPF pages in a form.•Starting a WPF window.•Hosting a master/detail form with a Windows Forms master and WPF details.•Hosting a master/detail form with a WPF master and Windows Forms details.•Hosting custom WPF controls that takes advantage of WPF features like 3-D Graphics, animations, Typography, document services, control templating. Example – Design a calculator that makes use of elliptical buttons that are animated as well.Key classes that promote WPF interoperability are WinFormsHost and ElementHost

10

Page 11: WPF Window

WPF Interoperability -WPF-based Application Hosting Windows Forms Controls

WPF provide controls with rich features set but however sometimes a WPF application would require controls that are available only for Windows Forms applications. Example Masked TextBox is available in Winforms but the same is not true with WPF.

WPF provides a solution to make such controls easily available for WPF applications by providing interoperability feature that allow for seamless integration between Winforms and WPF applications.

The key class that plays a major in promoting interoperability is WinformsHost Class

WinformsHost Class:

WPF promotes interoperability by providing a WinformsHost class that allows you to host a Windows Forms control in WPF application. It belongs to the namespace, System.Windows.Forms.Integration from assembly WindowsFormsIntegration .dll

The example on the presentation shows how to use MaskedTextBox on WPF form.

Now, let us look at steps required to perform interoperability by using Winforms control MaskedTextBox on WPF form.

1)Create a WPF Application project named WinToWPFInetroper.

2)In Solution Explorer, add a reference to the WindowsFormsIntegration assembly, which is named WindowsFormsIntegration.dll.

3)In Solution Explorer, add a reference to the Windows Forms assembly, which is named System.Windows.Forms.dll.

4)Open Window1.xaml in the WPF Designer and write the code as listed below

5)To the XAML file include prefixed namespace for System.Windows.Forms as shown in the XAML code below

6)XAML Markup

<Window x:Class="Window1"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:WinCtrl="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"

Title=" WinToWPF Inetroper ability" >

<StackPanel>

<WindowsFormsHost>

<WinCtrl:MaskedTextBox x:Name="mtbDate" Mask=“07/07/2011"/>

</WindowsFormsHost>

</ StackPanel >

</Window>

7) Build and Run the application to test the result. The result obtained will be as shown on the presentation.

11

Page 12: WPF Window

Hosting a WPF control in Windows Forms application

Windows application have a set of built –in controls, But however some of the controls like Expander or MediaElement are not available. To add more , windows applications also lack other features like 3-D, animations, document services and media services, styles, data template and control template. WPF makes such scenarios easy by providing interoperability feature that allows windows developers to incorporate WPF features while creating windows applications.

WPF provide controls with rich a rich set of built –in controls. Example Expander control-Represents the control that displays a header that has a collapsible window that displays content.

Let us look at scenario where a windows application would require Expander control to wrap a MonthCalendar control .

The key class that plays a major role in the above scenario easy and help promote interoperability is ElementHost Class.

ElementHost Class:

A class that can be used to host a Windows Presentation Foundation element in windows application.

It belongs to the namespace, System.Windows.Forms.Integration from assembly WindowsFormsIntegration .dll

The steps for using WPF Control Expander on Win form

1) Create Windows Forms application that hosts a WPF Expander control.

After creating a standard Windows Forms project , add reference to assemblies like System

PresentationCore, PresentationFramework, WindowsBase and System.Windows.Forms.Integration .

2) Drag ElementHost control from interoperability tab of the Toolbox, onto a Windows Form just like any

other Windows Forms control.

3) Add the code snippet as listed below, in the form constructor

// Create a WPF Expander

Expander expander = new Expander();

expander.Header = “WPF Expander”;

// Create a MonthCalendar and wrap it in a WindowsFormsHost

WindowsFormsHost host = new WindowsFormsHost();

host.Child = new MonthCalendar();

// Place the WindowsFormsHost in the Expander

expander.Content = host;

// Add the Expander to the ElementHost

elementHost.Child = expander;

4) Build and Run the application . The result obtained will be as shown on the presentation.

12

Page 13: WPF Window

An application may frequently require tasks that are triggered by a variety of different actions and through a variety of different user-interface elements, including main menus, context menus, keyboard shortcuts, and toolbars. These tasks can be coded as methods that are invoked through generic event handlers for these elements.

Many application tasks can be triggered by different elements so there is a need to code several event handlers that call the same application method.

Let us look at a simple example to describe the problem scenario.

Consider an application that includes a form with menu, context menu, toolbar with the other necessary element o complete the UI design.

This application makes use of a component that invoke a method named Open Document() that has the necessary logic to open the documents.

This method can be invoked in four ways:

1) Using a keyboard shortcut (Ctrl+O),

2) Using a main menu by choosing File ->Open,

3) Using a context menu (by right-clicking on the menu associated element and choosing Open and

4) Using a toolbar button.

Note : -To be continued…………..

13

Page 14: WPF Window

A developer’s solution for the scenario:

Developer would typically write three different event handlers to subscribe to the various input mechanisms, and then pass off the action to a common method.

Let us consider at certain points of time in application’s lifetime, it is necessary to temporarily disable the OpenDocument( ) task.

That is, enable and disable the appropriate controls whenever the corresponding actions are invalid by writing the code that does this and vice-versa later, can result in bad or disorganized code. Even worse, if it’s not done properly, may result in redundant code written incorrectly.

Fortunately, WPF’s support for Commands is designed to make such scenarios very easy.

(Note: The details of WPF Commands will be covered in the next slide – WPF Command Library)

14

Page 15: WPF Window

WPF Commands:

What are WPF Commands?

WPF Commands provides a new method for decoupling UI events, the handling of these events and also how to register multiple UI elements for these defined events.

Essentially Commands are a means by which shared actions can be grouped and invoked in several different ways within an application.

The WPF architects did not simply want to bring to XAML the standard programming model of controls and events. They wanted to address and simplify common scenarios faced by developers. One such scenario is having multiple input mechanisms that the user can do to perform an action.

Let us consider the example For example, to Cut a Text, users often can:

Click an Cut icon on the toolbar

Select the Edit>Cut menu option

Use a keyboard shortcut, such as Ctrl+X

In a normal scenario, a developer could handle the multiple exposures of commands such as Cut, Copy, and Paste with events fairly well. For example, define a generic event handler for each of the three actions and then attach each handler to the appropriate events on the relevant elements (the Cut Button on a toolbar, Use a keyboard shortcut such as Ctrl+X or Edit menu>Cut menu item).

In addition, probably to enable and disable the appropriate controls whenever the corresponding actions are invalid .

Example disabling any user interface for Paste when there is nothing on the clipboard by corresponding actions are invalid by writing the code that does this and vice-versa later could result in a bit more clumsy or redundant code.

Fortunately, WPF’s support for commands is designed to make such scenarios very easy. The support reduces the amount of code you need to write (and in some cases eliminating all procedural code), and it gives you more flexibility to change your user interface without breaking the back-end logic.

Why we should use Commands?

Developers can handle the multiple exposures of commands such as new, Open ,Cut, Copy, and Paste with events fairly well. For example, Developer defines a generic event handler for each of the above actions and then attach each handler to the appropriate events on the relevant elements (the Click event on a toolbar Button, the Keyboard shortcut keys event on the main menu item or context menu items). In addition, these could be enable and disable the appropriate controls whenever the corresponding actions are invalid (for example, disabling any user interface for Paste when there is nothing on the clipboard). This two-way communication gets a bit

more cumbersome, especially if developers do not want to hard-code a list of controls that need dupdating.

Fortunately, WPF’s support for commands is designed to make such scenarios very easy. The support reduces the amount of code you need to write (and in some cases eliminating all procedural code), and it gives you more flexibility to change your user interface without breaking the back-end logic.

What is the difference between an event handler and WPF Command?

A fundamental difference between commands and events is that commands do not exist in relation to controls, as there are many elements that will call them. In addition, commands run in the context of a single instance within the application runtime. Whenever an application invokes a command, tunneling and bubbling events are raised. Commands can be executed from anywhere within the application or programmatic logic.

Again what makes commands different from a simple event handler attached to a form element is that commands separate the semantics and the originator of an action from its logic. This allows for multiple and disparate sources to invoke the same command logic, and it allows the command logic to be customized for different targets.

All WPF Commands are routed commands.

Routed command source elements (invokers) can be decoupled from command targets (handlers)—they do not need direct references to one another, as they would if they were linked by an event handler.

Routed commands will automatically enable or disable all associated UI controls when the handler indicates the command is disabled.

Routed commands allow you to associate keyboard shortcuts and other forms of input gestures (ink gestures, for example) as another way to invoke the command.How can we use WPF Commands for common input actions?

WPF provides a library of common commands, which include; ApplicationCommands; ComponentCommands; NaviagationCommands; MediaCommands and EditingCommands.

15

Page 16: WPF Window

WPC command Library

WPF’s built-in commands are exposed as static properties of five different classes:

1)Application Commands from System.Windows.InputAssembly: PresentationCore

It provides command for common clipboard action such as Close, Copy, Cut, Delete, Find, Help, New, Open, Paste,Print, PrintPreview, Properties, Redo, Replace, Save, SaveAs, SelectAll, Stop, Undo etc.

2)ComponentCommands from Namespace: System.Windows.InputAssembly: PresentationCore.dll

They are used by user-interface components, for moving around and selecting content that are similar to (and even duplicate) some of the commands in the EditingCommands class such as MoveDown, MoveLeft, MoveRight, MoveUp, ScrollByLine, ScrollPageDown, ScrollPageLeft, ScrollPageRight, ScrollPageUp, SelectToEnd, SelectToHome, SelectToPageDown, SelectToPageUp etc.

16

Page 17: WPF Window

3) EditingCommands from Namespace: System.Windows.DocumentsAssembly: PresentationFramework.dll

These commands are document-editing commands like AlignCenter, AlignJustify, AlignLeft, AlignRight, CorrectSpellingError, DecreaseFontSize, DecreaseIndentation, EnterLineBreak, MoveDownByParagraph,

MoveDownByPage, MoveLeftByCharacter, MoveLeftByWord, and more

4)MediaCommands from Namespace: System.Windows.DocumentsAssembly: PresentationFramework.dll

A set of commands for managing multimedia on WPF form like ChannelDown, ChannelUp , DecreaseVolume, FastForward, IncreaseVolume, MuteVolume, NextTrack, Pause, Play, PreviousTrack, Record, Rewind, Select, Stop, and more

5) NavigationCommands from Namespace: System.Windows.InputAssembly: PresentationCore.dll

The commands that are used for navigation in WPF page-based applications and document based applications.

Commands for Page-based applications:

BrowseBack, BrowseForward, BrowseHome, BrowseStop, Favorites

Commands for Document-based applications:

FirstPage, GoToPage, LastPage, NextPage, PreviousPage, Refresh,

Search, Zoom, and more.

17

Page 18: WPF Window

The commanding system in WPF is based around the RoutedCommand and the RoutedEvent. •Command — the action to be executed Example “Application.New”

Command source — the object which invokes the command . The commands in the command library are always available. The easiest way to trigger them is to link them up to a control that implements the ICommandSource interface, which includes controls that derive from ButtonBase like Button, CheckBox , Menu, Toolbar Buttons and so or individual ListBoxItem objects, the Hyperlink etc.

Example

In the example below, a button control is linked to the ApplicationCommands.New command using the Command property:

<Button Command="ApplicationCommands.New">New</Button>

The above code is also equivalent to : <Button Command="New">New</Button>

Command binding — the object which maps the command logic to the command

When command are linked with the control , they are disabled by default. Because the command has no

attached binding, it’s considered to be disabled. To enable the Commands, they require some object that associates a command with the event handlers that implement the command. This is where CommandBindings

Come in.

What are CommandBindings?

A CommandBinding associates a command with the event handlers that implement the command.

The CommandBinding class contains a Command property, and PreviewExecuted, Executed, PreviewCanExecute, and CanExecute events. The event handlers attached to the PreviewCanExecute and CanExecute events determine if the command can execute on the current command target.

Role of CommandBinding : It perform following tasks

It decides the action to be take when command is triggered.

It identifies the target object on which the Command is to be executed. For example, the command might be limited to a single button, or it might be enabled over the entire window .

Example

CommandBinding Can be created declaratively in XAML or using managed code.

// Create the binding.

CommandBinding binding = new CommandBinding(ApplicationCommands.New);

// Attach the event handler.

binding.Executed += NewCommandHandler_Executed;

// Register the binding.

this.CommandBindings.Add(binding);

Where :- Executed of CommandBinding is associated with the event handler NewCommand_Executed

The XAML equivalent for the above code is as shown below :

<Window.CommandBindings>

<CommandBinding Command="ApplicationCommands.New" Executed="NewCommandHandler_Executed" CanExecute="OpenCmdCanExecute"/>

</Window.CommandBindings>

The event handlers associated with the CommandBinding are strictly written using managed code as how below

private void NewCommandHandler_Executed (object sender, ExecutedRoutedEventArgs e)

{

MessageBox.Show("New command triggered by " + e.Source.ToString());

}•Command target — the element that the command is being executed on. With regards to a RoutedCommand, the command target is the element at which routing of the Executed and CanExecute starts.

Example

<Button Command="Cut"

CommandTarget="{Binding ElementName=txtFile}">Cut</Button>

<Button Command="Copy"

CommandTarget="{Binding ElementName=txtFile}">Copy</Button>

<Button Command="Paste"

CommandTarget="{Binding ElementName=txtFile}">Paste</Button>

The command source can specify the command target explicitly. If not defined, the element with keyboard focus will be used as the command target. One of the benefits of using the element with keyboard focus as the command target is that it allows the application developer to use the same command source to invoke a command on multiple targets without having to keep track of the command target. For example, if a MenuItem invokes the Copy command in an application that has a TextBox control and a PasswordBox control, the target can be either the TextBox or PasswordBox depending on which control has keyboard focus.

18

Page 19: WPF Window

Executing the Commands:

Let us look at the example on the presentation.

<Window x:Class="Commands.TestNewCommand"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Title="TestNewCommand" Height="134" Width="281” >

<Window.CommandBindings>

<CommandBinding Command="ApplicationCommands.New" Executed="NewCommand" />

</Window.CommandBindings>

<StackPanel>

<Menu>

<MenuItem Header="File">

<MenuItem Command="New"></MenuItem>

</MenuItem>

</Menu>

<Button Margin="5" Padding="5" Command="ApplicationCommands.New"

ToolTip="{x:Static ApplicationCommands.New}">New</Button>

</StackPanel>

</Window>

Here the CommandBinding link the Application.New command with event handler –NewCommand via its own event –Executed. The event handler –NewCommand implements the logic for the command. In this example there are multiple command sources – Button and Menu Item.

So when either the Button or Menu is clicked, it invokes ApplicationCommands.New that fires Executed event of CommandBinding. This in turn invokes the NewCommand event handler causing the MessageBox to be displayed (implementation logic for Command) as shown on the presentation.

Summary :

WPF window

Windows are the basic elements in any Standalone or desktop application. They allow the user to interact with a standalone application.

The implementation of a typical window includes both appearance and behavior that can be coded in XAML or managed code.

Typically a WPF Windows is divided into two distinct sections

1) Client Area

2) Non Client Area.

WPF Interoperability

WPF Interoperability feature promotes using WPF control in Windows application and vice –versa . WPF provides a System.Windows.Forms.Integration namespace that makes such scenarios easy. This namespace provides key classes like ElementHost and WinFormsHost that play a major role in interoperability feature.

Interoperability can be implemented by writing a XAML markup or by writing managed code

The example on the presentation -WPF-based Application Hosting Windows Forms Controls demonstrates implementing interoperability by writing XAML code only.

The example on the presentation -Windows Forms Application Hosting WPF Control demonstrates implementing interoperability by writing managed code only.

WPF Commands:

WPF Commands provides a new method for decoupling UI events, the handling of these events and also specifies how to register multiple UI elements for these defined events. They allow shared actions to be grouped and invoked in several different ways within an application. Canonical examples of commands are Cut, Copy, Paste, New, Open etc .

WPF commands can be implemented by using one of the pre-defined RoutedCommand class from WPF Command Library: ApplicationCommands, ComponentCommands, EditingCommands, MediaCommands and NavigationCommands.

WPF Command Model include Commands from Command Library, Command Source, Command Target, CommandBindings.

19

Page 20: WPF Window

20

Page 21: WPF Window

21

Page 22: WPF Window

22

Page 23: WPF Window

23

Page 24: WPF Window

24