Title: Windows Presentation Foundation: Applications
1Windows Presentation Foundation Applications
2Introduction
- WPF is about creating presentations with
effective presentation of information. - Building Blocks of UI are windows, pages and user
controls. - Application-level services are navigation,
resources, configuration and hosting
3Application Principles
- Scalability, Web-Style and Desktop-style.
- System should extend from light weight Web
applications to full blown desktop applications. - Take the best features of Web-style and
Desktop-style.
4Scalable Applications
- Simple example
- HelloWorld.xaml
- ltPage
- xmlns'http//schemas.microsoft.com/winfx/2006/xam
l/presentation' - WindowTitle'Hello World'gt
- ltTextBlock FontSize'24'gtHello Worldlt/TextBlockgt
- lt/Pagegt
5Scalable Applications (Contd..)
6Scalable Applications (Contd..)
- If need to write some code to page
- HelloWorld.xaml
- ltPage
- xClass'EssentialWPF.HelloWorld'
- xmlns'http//schemas.microsoft.com/winfx/2006/xam
l/presentation' - xmlnsx'http//schemas.microsoft.com/winfx/2006/x
aml' - WindowTitle'Hello World'gt
- ltTextBlock xName'text1' FontSize'24'gtHello
Worldlt/TextBlockgt - lt/Pagegt
7Scalable Applications (Contd..)
- HelloWorld.xaml.cs
- using System
- using System.Windows
- using System.Windows.Controls
- namespace EssentialWPF
- public partial class HelloWorld Page
- public HelloWorld()
- InitializeComponent()
- text1.Text "Now is " DateTime.Now.ToString()
-
-
8Scalable Applications (Contd..)
- App.xaml
- ltApplication
- xmlns'http//schemas.microsoft.com/winfx/2006/xam
l/presentation' - StartupUri'helloworld.xaml' /gt
9Scalable Applications (Contd..)
- Project file to instruct MSBuild how to compile
the project - ltProject DefaultTargets"Build"
- xmlns"http//schemas.microsoft.com/developer/msbu
ild/2003"gt - lt!-- ...rest of project file... --gt
- ltPropertyGroupgt
- ltHostInBrowsergttruelt/HostInBrowsergt
- lt/PropertyGroupgt
- ltItemGroupgt
- ltPage Include"HelloWorld.xaml" /gt
- ltApplicationDefinition Include"App.xaml" /gt
- ltCompile Include"HelloWorld.xaml.cs" /gt
- lt/ItemGroupgt
- lt!-- ...rest of project file... --gt
- lt/Projectgt
10Scalable Applications (Contd..)
- On building HelloWorld.xbap
- XBAP(XAML Browser Application)
11Scalable Applications (Contd..)
- Converting the browser application to Desktop
application. - ltProject DefaultTargets"Build"
xmlns"http//schemas.microsoft.com/ - developer/msbuild/2003"gt
- lt!-- ...rest of project file... --gt
- ltPropertyGroupgt
- ltHostInBrowsergtfalselt/HostInBrowsergt
- lt/PropertyGroupgt
- lt!-- ...rest of project file... --gt
- lt/Projectgt
12Scalable Applications (Contd..)
- On rebuilding we get HelloWorld.exe
13Web Style
- Application model in WPF is to integrate the best
of desktop programming and Web programming. - How to add navigation in the browser or desktop
window? - Using Hyperlink control
- Second-page.xaml
- ltPage
- xmlns'http//schemas.microsoft.com/winfx/2006/xam
l/presentation' - WindowTitle'Second Page'gt
- ltTextBlock FontSize'24'gtWelcome to page
2lt/TextBlockgt - lt/Pagegt
14Web Style (contd..)
- HelloWorld.xaml
- ltPage ... WindowTitle'Hello World'gt
- ltStackPanelgt
- ltTextBlock xName'text1' FontSize'24'gtHello
Worldlt/TextBlockgt - ltTextBlock FontSize'24'gt
- ltHyperlink NavigateUri'second-page.xaml'gt
- Goto Page 2
- lt/Hyperlinkgt
- lt/TextBlockgt
- lt/StackPanelgt
- lt/Pagegt
15Web Style (contd..)
- Web-style applications have the application root
as a base that is, relative URIs are relative to
the application. - Adding an image to the second page
- ltPage
- xmlns'http//schemas.microsoft.com/winfx/2006/xam
l/presentation' - WindowTitle'Second Page'gt
- ltTextBlock FontSize'24'gtWelcome to page 2
- ltImage
- Source'http//blog.simplegeek.com/images/img_1476
-small.png' /gt - lt/TextBlockgt
- lt/Pagegt
16Web Style (contd..)
17Desktop styles
- WPF strives to unify the various windowing models
so that they could also be used in Web
applications. - Windowing models are shown in the next slide.
18Desktop style (contd..)
19Application
- The Application object is responsible for
managing the lifetime of the application,
tracking the visible windows, dispensing
resources, and managing the global state of the
application. - A WPF application logically starts executing
when the Run method is invoked on an instance of
the Application object.
20Application (contd..)
- HelloWorld Example
- using System
- using System.Windows
- namespace EssentialWPF
- static class Program STAThread
- static void Main()
- Application app new Application()
- Window w new Window()
- w.Title "Hello World"
- w.Show()
- app.Run()
-
-
-
21Application (contd..)
- The call to Run is normally the last line of the
entry-point function. - Run starts sending events and messages to
components in the WPF application. - Run will exist until the application is shutting
down.
22Application (contd..)
- To encapsulate startup logic
- // program.cs
- using System
- using System.Windows
- namespace EssentialWPF
- static class Program
- STAThread
- static void Main()
- MyApp app new MyApp()
- app.Run()
-
23Application (contd..)
- class MyApp Application
- public MyApp()
- Window w new Window()
- w.Title "Hello World"
- w.Show()
-
-
-
24Application (contd..)
- To reduce the boilerplate code.
- To allow declarative programming.
- To ensure setting of STAThread attribute,
creating Application object and calling run. - WPF allows us to define application in markup.
25Application (contd..)
- lt!-- myapp.xaml --gt
- ltApplication xClass'EssentialWPF.MyApp' ... /gt
- // myapp.xaml.cs
- using System
- using System.Windows
- namespace EssentialWPF
- partial class MyApp Application
- public MyApp()
- Window w new Window()
- w.Title "Hello World"
- w.Show()
-
26Application (contd..)
- lt!-- sample.csproj --gt
- ltProject
- DefaultTargets'Build'
- xmlns'http//schemas.microsoft.com/developer/msbu
ild/2003'gt - ...
- ltItemGroupgt
- ltApplicationDefinition Include'myapp.xaml' /gt
- ltCompile Include'myapp.xaml.cs' /gt
- lt/ItemGroupgt
- ...
- lt/Projectgt
27Application (contd..)
- The boilerplate code generated by the build
system. - namespace EssentialWPF
- /// ltsummarygt
- /// MyApp
- /// lt/summarygt
- public partial class MyApp System.Windows.Applic
ation - /// ltsummarygt
- /// Application entry point
- /// lt/summarygt
- System.STAThreadAttribute()
- System.Diagnostics.DebuggerNonUserCodeAttribute()
- public static void Main()
- EssentialWPF.MyApp app new EssentialWPF.MyApp()
- app.Run()
-
-
28Application (contd..)
- Lifetime of application
- 1. Application object is constructed.
- 2. Run method is called.
- 3. Application.Startup event is raised.
- 4. User code constructs one or more Window
objects. - 5. Application.Shutdown method is called.
- 6. Application.Exit event is raised.
- 7. Run method completes.
29Application (contd..)
- Initialize the application in one of two ways
(1) from the constructor of the Application
object, or (2) by handling the Startup event. - lt!-- myapp.xaml --gt
- ltApplication
- xClass'EssentialWPF.MyApp'
- ...
- Startup'MyApp_Startup'
- /gt
- // myapp.xaml.cs
- using System
- using System.Windows
- namespace EssentialWPF
- partial class MyApp Application
- public MyApp()
-
- void MyApp_Startup(object sender,
StartupEventArgs e) - Window w new Window()
- w.Title "Hello World"
- w.Show()
30Error Handling
- Exceptions from which WPF cannot recover
StackOverflow-Exception, OutOfMemoryException,
and ThreadAbortException. - Except with these three special exceptions, in
the WPF all code returns to a consistent state
after an exception occurs. This means that
developers can perform their own application
recovery logic
31Error Handling (contd..)
- WPFs default is that the application will fail
if any asynchronous or uncaught exception occurs. - The Application object offers an event,
DispatcherUnhandledException using which an
application can implement any policy for dealing
with exceptions. - This event is raised when the dispatcher sees an
exception bubble up.
32Error Handling (contd..)
- public class DispatcherUnhandledExceptionEventArgs
- DispatcherEventArgs
- public Exception Exception get
- public bool Handled get set
-
- Implement a policy that any failure will be
ignored but written out to a log, and request
that the user submit the error to the system
administrator.
33Error Handling (contd..)
- void Failure(object sender, DispatcherUnhandledExc
eptionEventArgs e) -
- using (StreamWriter errorLog
- new StreamWriter("c\\error.log", true))
-
- errorLog.WriteLine("Error _at_ "
DateTime.Now.ToString("R")) - errorLog.WriteLine(e.Exception.ToString())
-
- e.Handled true
- MessageBox.Show("An error occured, please report
this " - "to your system administrator with the "
- "contents of the file 'c\\error.log'")
-
34Managing state
- State commonly spans top-level UI components for
example, we may want to track the current list of
open documents in an application, or the current
state of a network connection. - The simplest way to store state on the
application is using the Properties property
available on Application. Properties is typed as
System.Collections.IDictionary
35Managing state (contd..)
- Extending the error handler to cache the last
error seen - // myapp.xaml.cs
- public partial class MyApp Application
- ..
- void Failure(object sender, DispatcherUnhandledExc
eptionEventArgs e) - using (StreamWriter errorLog
- new StreamWriter("c\\error.log", true))
- errorLog.WriteLine("Error _at_ "
DateTime.Now.ToString("R")) - errorLog.WriteLine(e.Exception.ToString())
-
- e.Handled true
- this.Properties"LastError" e.Exception
-
- ...
36Managing state (contd..)
- Because Properties is a simple object/object
dictionary, we need to continually cast the data
we store there. - // myapp.xaml.cs
- public partial class MyApp Application
- private Exception _lastError
- public Exception LastError
- get return _lastError
- set _lastError value
-
- ...
- void Failure(object sender, DispatcherUnhandledExc
eptionEventArgs e) - using (StreamWriter errorLog
- new StreamWriter("c\\error.log", true))
- errorLog.WriteLine("Error _at_ "
DateTime.Now.ToString("R")) - errorLog.WriteLine(e.Exception.ToString())
-
- e.Handled true
- this.LastError e.Exception
-
37Resources and Configuration
- To have states persistent across runs of
applications and scoped per user we need to use
resources and configuration services. - 3 different ways to categorize application state
configuration, content and document.
38Configuration state
- Configuration state consists of settings
associated with a user or machine and can
generally be modified by a user or administrator
at runtime or deployment. - System.Configuration APIs are the right thing to
use. - To start using the configuration system, we need
to define the object model for our settings.
39Configuration state (contd..)
- Need to derive our settings class from
ApplicationSettingsBase and provide some metadata
about the property. - public class AppSettings ApplicationSettingsBase
- public AppSettings() base()
-
- UserScopedSetting
- DefaultSettingValue("0")
- public int RunCount
- get return (int)this"RunCount"
- set this"RunCount" value
-
40Configuration state (contd..)
- After defining the object model for the settings
set up the configuration file bindings and expose
the settings through the Application object. - To set up the configuration file bindings, we
need to register the AppSettings class with the
configuration system by adding a section in the
app.config file.
41Configuration state (contd..)
- To expose the settings on the application object,
we can create a public instance property - public partial class MyApp Application
- AppSettings _settings new AppSettings()
- public AppSettings Settings
- get
- return _settings
-
-
- public MyApp()
- this.Exit MyApp_Exit
- this.Startup AppStartup
42Configuration state (contd..)
- void MyApp_Exit(object sender, ExitEventArgs e)
- Settings.Save()
-
- void AppStartup(object sender, StartupEventArgs
args) - Window w new Window()
- w.Title "You ran this " (Settings.RunCount)
" times" - w.Show()
-
-
43Content state
- Content state, also commonly called resources
(links to images, media, documents, etc.), is
determined at authoring time. - To reference something either relative to the
application or actually embedded in the
application binary the resource loading APIs are
used.
44Content state (contd..)
- Types of resources and how they can be used.
45Document
- Document state is the set of data associated with
a user document (like a Microsoft Word document
or image file). - Although .NET has some services for creating and
manipulating documents, WPF provides no default
framework for managing document state. - This is something that application authors must
integrate on their own.
46Windows
- The base type for all windows in WPF is
System.Windows.Window. Window is generally used
for SDI windows and dialogs. - lt!-- Window1.xaml --gt
- ltWindow ...
- xClass'EssentialWPF.Window1'
- Visibility'Visible'
- Title'This is a Window!'
- gt
- lt/Windowgt
- // Window1.cs
- namespace EssentialWPF
- public partial class Window1 Window
- public Window1()
- InitializeComponent()
-
-
47Windows (contd..)
- The phases in the life of a Window
- 1. Constructor is called.
- 2. Window.Initialized event is raised.
- 3. Window.Activated event is raised.13
- 4. Window.Loaded event is raised.
- 5. Window.ContentRendered event is raised.
- 6. User interacts with the window.
- 7. Window.Closing event is raised.
- 8. Window.Unloaded event is raised.
- 9. Window.Closed event is raised.
48Windows (contd..)
- Displaying a window Show, ShowDialog and
Visibility prorperty. - ShowDialog used to display the dialog modally.
- lt!-- Window1.xaml --gt
- ltWindow ... Title'Starter Window' gt
- ltStackPanelgt
- ltButton Click'ShowMethod'gtShowlt/Buttongt
- ltButton Click'UseVisibilityProperty'gtVisibility
Visiblelt/Buttongt - ltButton Click'ShowDialogMethod'gtShowDialoglt/Butto
ngt - lt/StackPanelgt
- lt/Windowgt
49Windows (contd..)
- // Window1.xaml.cs
- ...
- void ShowMethod(object sender, RoutedEventArgs e)
- Window w new Window()
- w.Title "Show"
- w.Show()
-
- void UseVisibilityProperty(object sender,
RoutedEventArgs e) - Window w new Window()
- w.Title "Visibility Visible"
- w.Visibility Visibility.Visible
-
- void ShowDialogMethod(object sender,
RoutedEventArgs e) - Window w new Window()
- w.Title "ShowDialog"
- w.Owner this
- w.WindowStartupLocation WindowStartupLocation.Ce
nterOwner - w.ShowInTaskbar false
- w.ShowDialog()
50Windows (contd..)
- Sizing and position determined using
- WindowStartupLocation property, combined with the
Top and Left properties. - SizeToContent property in combination with the
Width and Height properties.
51Windows (contd..)
- The Application object is notified whenever a
window is closed. - We can also enumerate all the currently open
windows using the Application.Windows property.
52User Controls
- User controls are used as a way of encapsulating
parts of the UI, and custom controls are used as
a way to build reusable controls for other
applications to consume. - ltContentControl ...
- xClass'EssentialWPF.MyUserControl'
- gt
- ltButton Click'ButtonClicked'gtHello
Worldlt/Buttongt - lt/ContentControlgt
53User Controls (contd..)
- public partial class MyUserControl
ContentControl - public MyUserControl()
- InitializeComponent()
-
- void ButtonClicked(object sender, RoutedEventArgs
e) - MessageBox.Show("Howdy!")
-
-
- ltWindow ...
- xClass'EssentialWPF.UserControlHost'
- xmlnsl'clr-namespaceEssentialWPF'
- Title'User Controls'
- gt
- ltStackPanelgt
- ltlMyUserControl /gt
- ltlMyUserControl /gt
54User Controls (contd..)
55Navigation and Pages
- Logical model for navigation
56Navigation and Pages (contd..)
- public class Page1 Page
- public Page1()
- this.WindowTitle "Page 1"
-
-
- public class NavExample NavigationWindow
- public NavExample()
- Navigate(new Page1())
-
-
- public class Page2 Page
- public Page2()
- WindowTitle "Page 2"
-
57Navigation and Pages (contd..)
- public class Page1 Page
- public Page1()
- TextBlock block new TextBlock()
- Hyperlink link new Hyperlink()
- link.Click LinkClicked
- link.Inlines.Add("Click for page 2")
- block.Inlines.Add(link)
- Content block
- WindowTitle "Page 1"
-
- void LinkClicked(object sender, RoutedEventArgs
e) - NavigationService.Navigate(new Page2())
-
-
58Navigation and Pages (contd..)
59Navigation and Pages (contd..)
- Replace all code with markup.
- lt!-- page1.xaml --gt
- ltPage ...
- WindowTitle'Page 1'gt
- ltTextBlockgt
- ltHyperlink NavigateUri'page2.xaml'gt
- Click for page 2
- lt/Hyperlinkgt
- lt/TextBlockgt
- lt/Pagegt
60Navigation and Pages (contd..)
- lt!-- page2.xaml --gt
- ltPage ...
- WindowTitle'Page 2'gt
- lt/Pagegt
- lt!-- navexample.xaml --gt
- ltNavigationWindow ...
- xClass'EssentialWPF.NavExample'
- Source'page1.xaml'gt
- lt/NavigationWindowgt
- lt!-- app.xaml --gt
- ltApplication ...
- xClass'EssentialWPF.App'
- StartupUri'page1.xaml'gt
- lt/Applicationgt
61Navigation and Pages (contd..)
- We can pass state between pages by leveraging the
properties dictionary on Application but it is
merely a global object. - Another option is the navigation-State argument
on Naviagte can be used. - public class NavigationService
- ...
- public bool Navigate(object root)
- public bool Navigate(Uri source)
- public bool Navigate(object root, object
navigationState) - public bool Navigate(Uri source, object
navigationState) - ...
62Controlling Navigation
- public class NavigationService
-
- ...
- public event LoadCompletedEventHandler
LoadCompleted - public event NavigatedEventHandler Navigated
- public event NavigatingCancelEventHandler
Navigating - public event NavigationProgressEventHandler
NavigationProgress - public event NavigationStoppedEventHandler
NavigationStopped - ...
63Controlling Journal
- public sealed class NavigationService
- public bool CanGoBack get
- public bool CanGoForward get
- public void AddBackEntry(CustomContentState
state) - public void GoBack()
- public void GoForward()
- public JournalEntry RemoveBackEntry()
64Functional Navigation and Page Functions
- Functional form of navigation in which navigation
is modeled like a function call.
65Functional Navigation and Page Functions
- public class Program
- STAThread
- static void Main()
- Application app new Application()
- NavigationWindow w new NavigationWindow()
- w.Show()
- w.Navigate(new Welcome())
- app.Run()
-
66Functional Navigation and Page Functions
- public class Welcome PageFunctionltobjectgt
- public Welcome()
- TextBlock block new TextBlocks()
- block.FontSize24
- block.Inlines.Add("Welcome!")
- Hyperlink link new Hyperlink()
- link.Inlines.Add("Next")
- link.Click DoSayHello
- block.Inlines.Add(link)
- Content block
-
- void DoSayHello(object sender, RoutedEventArgs e)
- NavigationService.Navigate(new SayHello())
-
67Functional Navigation and Page Functions
- public class SayHello PageFunctionltobjectgt
- public SayHello()
- // We need to be kept alive, so that we can
listen - // to the return of GetName
- //
- this.KeepAlive true
- // When this page is initialized, we first need
to get - // the name from the user
- //
- this.Initialized DoGetName
-
- void DoGetName(object sender, EventArgs e)
- // To get the name from the user, we navigate to
- // GetName, and listen for GetName to complete
(Return) - //
- GetName get new GetName()
- get.Return GetNameReturned
- NavigationService.Navigate(get)
68Functional Navigation and Page Functions
- void GetNameReturned(object sender,
ReturnEventArgsltstringgt e) - // When GetName returns, we can update the
content - // of this page to say hello to the user
- //
- Label label new Label()
- label.Content string.Format("Hello 0",
e2.Result) - Content label
-
-
- public class GetName PageFunctionltstringgt
- public GetName()
- StackPanel stack new StackPanel()
- Label label new Label()
- label.Content "What is your name?"
- stack.Children.Add(label)
69Functional Navigation and Page Functions
- TextBox nameBox new TextBox()
- stack.Children.Add(nameBox)
- Button done new Button()
- done.Content "Done"
- done.Click ReturnName
- stack.Children.Add(done)
- Content stack
-
- void ReturnName(object sender, RoutedEventArgs e)
- OnReturn(new ReturnEventArgsltstringgt(nameBox.Text)
) -
70References
- Essential Windows Presentation Foundation by
Chris Anderson