Presentation is loading. Please wait.

Presentation is loading. Please wait.

Windows Presentation Foundation: Applications

Similar presentations


Presentation on theme: "Windows Presentation Foundation: Applications"— Presentation transcript:

1 Windows Presentation Foundation: Applications
Pradeep Kumar Vijay

2 Introduction 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

3 Application 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.

4 Scalable Applications
Simple example HelloWorld.xaml <Page xmlns=' WindowTitle='Hello World'> <TextBlock FontSize='24'>Hello World</TextBlock> </Page>

5 Scalable Applications (Contd..)

6 Scalable Applications (Contd..)
If need to write some code to page HelloWorld.xaml <Page x:Class='EssentialWPF.HelloWorld' xmlns=' xmlns:x=' WindowTitle='Hello World'> <TextBlock x:Name='text1' FontSize='24'>Hello World</TextBlock> </Page>

7 Scalable 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(); }

8 Scalable Applications (Contd..)
App.xaml <Application xmlns=' StartupUri='helloworld.xaml' />

9 Scalable Applications (Contd..)
Project file to instruct MSBuild how to compile the project <Project DefaultTargets="Build" xmlns=" <!-- ...rest of project file... --> <PropertyGroup> <HostInBrowser>true</HostInBrowser> </PropertyGroup> <ItemGroup> <Page Include="HelloWorld.xaml" /> <ApplicationDefinition Include="App.xaml" /> <Compile Include="HelloWorld.xaml.cs" /> </ItemGroup> </Project>

10 Scalable Applications (Contd..)
On building HelloWorld.xbap XBAP(XAML Browser Application)

11 Scalable Applications (Contd..)
Converting the browser application to Desktop application. <Project DefaultTargets="Build" xmlns=" developer/msbuild/2003"> <!-- ...rest of project file... --> <PropertyGroup> <HostInBrowser>false</HostInBrowser> </PropertyGroup> </Project>

12 Scalable Applications (Contd..)
On rebuilding we get HelloWorld.exe

13 Web 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 <Page xmlns=' WindowTitle='Second Page'> <TextBlock FontSize='24'>Welcome to page 2</TextBlock> </Page>

14 Web Style (contd..) HelloWorld.xaml
<Page ... WindowTitle='Hello World'> <StackPanel> <TextBlock x:Name='text1' FontSize='24'>Hello World</TextBlock> <TextBlock FontSize='24'> <Hyperlink NavigateUri='second-page.xaml'> Goto Page 2 </Hyperlink> </TextBlock> </StackPanel> </Page>

15 Web 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 <Page xmlns=' WindowTitle='Second Page'> <TextBlock FontSize='24'>Welcome to page 2 <Image Source=' /> </TextBlock> </Page>

16 Web Style (contd..) The output…

17 Desktop 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.

18 Desktop style (contd..)

19 Application 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.

20 Application (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(); }

21 Application (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.

22 Application (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(); }

23 Application (contd..) class MyApp : Application { public MyApp() {
Window w = new Window(); w.Title = "Hello World"; w.Show(); }

24 Application (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.

25 Application (contd..) <!-- myapp.xaml -->
<Application x:Class='EssentialWPF.MyApp' ... /> // 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(); }

26 Application (contd..) <!-- sample.csproj --> <Project
DefaultTargets='Build' xmlns=' ... <ItemGroup> <ApplicationDefinition Include='myapp.xaml' /> <Compile Include='myapp.xaml.cs' /> </ItemGroup> </Project>

27 Application (contd..) The boilerplate code generated by the build system. namespace EssentialWPF { /// <summary> /// MyApp /// </summary> public partial class MyApp : System.Windows.Application { /// Application entry point [System.STAThreadAttribute()] [System.Diagnostics.DebuggerNonUserCodeAttribute()] public static void Main() { EssentialWPF.MyApp app = new EssentialWPF.MyApp(); app.Run(); }

28 Application (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.

29 Application (contd..) Initialize the application in one of two ways: (1) from the constructor of the Application object, or (2) by handling the Startup event. <!-- myapp.xaml --> <Application x:Class='EssentialWPF.MyApp' ... Startup='MyApp_Startup' />` // 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();

30 Error 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

31 Error Handling (contd..)
WPF’s 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.

32 Error 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.

33 Error Handling (contd..)
void Failure(object sender, DispatcherUnhandledExceptionEventArgs e) { using (StreamWriter errorLog = new StreamWriter("c:\\error.log", true)) " + 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'");

34 Managing 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

35 Managing state (contd..)
Extending the error handler to cache the last error seen // myapp.xaml.cs public partial class MyApp : Application { .. void Failure(object sender, DispatcherUnhandledExceptionEventArgs e) { using (StreamWriter errorLog = new StreamWriter("c:\\error.log", true)) { " + DateTime.Now.ToString("R")); errorLog.WriteLine(e.Exception.ToString()); } e.Handled = true; this.Properties["LastError"] = e.Exception; ...

36 Managing 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, DispatcherUnhandledExceptionEventArgs e) { using (StreamWriter errorLog = new StreamWriter("c:\\error.log", true)) { " + DateTime.Now.ToString("R")); errorLog.WriteLine(e.Exception.ToString()); e.Handled = true; this.LastError = e.Exception;

37 Resources 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.

38 Configuration 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.

39 Configuration 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; }

40 Configuration 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.

41 Configuration 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;

42 Configuration 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();

43 Content 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.

44 Content state (contd..) Types of resources and how they can be used.

45 Document 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.

46 Windows The base type for all windows in WPF is System.Windows.Window. Window is generally used for SDI windows and dialogs. <!-- Window1.xaml --> <Window ... x:Class='EssentialWPF.Window1' Visibility='Visible' Title='This is a Window!' > </Window> // Window1.cs namespace EssentialWPF { public partial class Window1 : Window { public Window1() { InitializeComponent(); }

47 Windows (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.

48 Windows (contd..) Displaying a window: Show, ShowDialog and Visibility prorperty. ShowDialog used to display the dialog modally. <!-- Window1.xaml --> <Window ... Title='Starter Window' > <StackPanel> <Button Click='ShowMethod'>Show</Button> <Button Click='UseVisibilityProperty'>Visibility = Visible</Button> <Button Click='ShowDialogMethod'>ShowDialog</Button> </StackPanel> </Window>

49 Windows (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) { w.Title = "Visibility = Visible"; w.Visibility = Visibility.Visible; void ShowDialogMethod(object sender, RoutedEventArgs e) { w.Title = "ShowDialog"; w.Owner = this; w.WindowStartupLocation = WindowStartupLocation.CenterOwner; w.ShowInTaskbar = false; w.ShowDialog();

50 Windows (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.

51 Windows (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.

52 User 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. <ContentControl ... x:Class='EssentialWPF.MyUserControl' > <Button Click='ButtonClicked'>Hello World</Button> </ContentControl>

53 User Controls (contd..) public partial class MyUserControl : ContentControl { public MyUserControl() { InitializeComponent(); } void ButtonClicked(object sender, RoutedEventArgs e) { MessageBox.Show("Howdy!"); <Window ... x:Class='EssentialWPF.UserControlHost' xmlns:l='clr-namespace:EssentialWPF' Title='User Controls' > <StackPanel> <l:MyUserControl /> </StackPanel> </Window> Figure

54 User Controls (contd..)

55 Navigation and Pages Logical model for navigation

56 Navigation 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";

57 Navigation 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());

58 Navigation and Pages (contd..)

59 Navigation and Pages (contd..)
Replace all code with markup. <!-- page1.xaml --> <Page ... WindowTitle='Page 1'> <TextBlock> <Hyperlink NavigateUri='page2.xaml'> Click for page 2 </Hyperlink> </TextBlock> </Page>

60 Navigation and Pages (contd..)
<!-- page2.xaml --> <Page ... WindowTitle='Page 2'> </Page> <!-- navexample.xaml --> <NavigationWindow ... x:Class='EssentialWPF.NavExample' Source='page1.xaml'> </NavigationWindow> <!-- app.xaml --> <Application ... x:Class='EssentialWPF.App' StartupUri='page1.xaml'> </Application>

61 Navigation 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); }

62 Controlling Navigation
public class NavigationService { ... public event LoadCompletedEventHandler LoadCompleted; public event NavigatedEventHandler Navigated; public event NavigatingCancelEventHandler Navigating; public event NavigationProgressEventHandler NavigationProgress; public event NavigationStoppedEventHandler NavigationStopped; }

63 Controlling 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(); }

64 Functional Navigation and Page Functions
Functional form of navigation in which navigation is modeled like a function call.

65 Functional 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(); }

66 Functional Navigation and Page Functions
public class Welcome : PageFunction<object> { public Welcome() { TextBlock block = new TextBlocks(); block.FontSize=24; 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());

67 Functional Navigation and Page Functions
public class SayHello : PageFunction<object> { 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);

68 Functional Navigation and Page Functions
void GetNameReturned(object sender, ReturnEventArgs<string> 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 : PageFunction<string> { public GetName() { StackPanel stack = new StackPanel(); label.Content = "What is your name?"; stack.Children.Add(label);

69 Functional 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 ReturnEventArgs<string>(nameBox.Text));

70 References Essential Windows Presentation Foundation by Chris Anderson


Download ppt "Windows Presentation Foundation: Applications"

Similar presentations


Ads by Google