1 / 70

Windows Presentation Foundation: Applications

Windows Presentation Foundation: Applications. Pradeep Kumar Vijay. Introduction. WPF is about creating presentations with effective presentation of information. Building Blocks of UI are windows, pages and user controls.

terah
Download Presentation

Windows Presentation Foundation: Applications

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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='http://schemas.microsoft.com/winfx/2006/xaml/presentation' 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='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' 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='http://schemas.microsoft.com/winfx/2006/xaml/presentation' StartupUri='helloworld.xaml' />

  9. Scalable Applications (Contd..) • Project file to instruct MSBuild how to compile the project <Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <!-- ...rest of project file... --> <PropertyGroup> <HostInBrowser>true</HostInBrowser> </PropertyGroup> <ItemGroup> <Page Include="HelloWorld.xaml" /> <ApplicationDefinition Include="App.xaml" /> <Compile Include="HelloWorld.xaml.cs" /> </ItemGroup> <!-- ...rest of project file... --> </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="http://schemas.microsoft.com/ developer/msbuild/2003"> <!-- ...rest of project file... --> <PropertyGroup> <HostInBrowser>false</HostInBrowser> </PropertyGroup> <!-- ...rest of project file... --> </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='http://schemas.microsoft.com/winfx/2006/xaml/presentation' 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='http://schemas.microsoft.com/winfx/2006/xaml/presentation' WindowTitle='Second Page'> <TextBlock FontSize='24'>Welcome to page 2 <Image Source='http://blog.simplegeek.com/images/img_1476-small.png' /> </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='http://schemas.microsoft.com/developer/msbuild/2003'> ... <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 { /// <summary> /// Application entry point /// </summary> [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)) { errorLog.WriteLine("Error @ " + 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)) { errorLog.WriteLine("Error @ " + 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)) { errorLog.WriteLine("Error @ " + 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) { 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.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.

More Related