Windows Presentation Foundation: Applications

Slides:



Advertisements
Similar presentations
Module 1: Creating an Application by Using Windows Presentation Foundation Overview of WPF Creating a Simple WPF Application Handling Events and Commands.
Advertisements

1111 Creating ASPX Controls Programatically Objectives You will be able to Dynamically add controls to a page. Dynamically alter properties of controls.
Win8 on Intel Programming Course Desktop : Sensors Cédric Andreolli Intel Software
 2007 Dr. Natheer Khasawneh. Chapter 13. Graphical User Interface Concepts: Part 1.
The Web Warrior Guide to Web Design Technologies
1 Chapter 12 Working With Access 2000 on the Internet.
Internet Technologies 1 Master of Information System Management Java Server Faces Model/View/Controller Design Pattern for Web Development Slides.
Introduction to the C# Programming Language for the VB Programmer.
Copyright © 2012 Pearson Education, Inc. Chapter 2 Introduction to Visual C#
1 An Introduction to Visual Basic Objectives Explain the history of programming languages Define the terminology used in object-oriented programming.
Christopher M. Pascucci Basic Structural Concepts of.NET Browser – Server Interaction.
ASP.Net, Web Forms and Web Controls 1 Outline Introduction Simple HTTP Transaction System Architecture Creating and Running a Simple Web Form Example Web.
Tutorial: Introduction to ASP.NET Internet Technologies and Web Application 4 th February 2010.
Introduction to the Enterprise Library. Sounds familiar? Writing a component to encapsulate data access Building a component that allows you to log errors.
Architecture Of ASP.NET. What is ASP?  Server-side scripting technology.  Files containing HTML and scripting code.  Access via HTTP requests.  Scripting.
JavaScript & jQuery the missing manual Chapter 11
Microsoft Visual Basic 2005: Reloaded Second Edition
Software Architecture for ColdFusion Developers Unit 4: Application Events and Global Variables.
Java Programming, 3e Concepts and Techniques Chapter 3 Section 65 – Manipulating Data Using Methods – Java Applet.
An Introduction to Silverlight Matt Harrington Developer Evangelist, Microsoft October 20, 2011.
Windows Presentation Foundation. Agenda Introduction Developing Applications WPF and WF interoperability Custom Controls Styles and Templates Data Binding.
IE 411/511: Visual Programming for Industrial Applications
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC BUILDING BLOCKS Bilal Munir Mughal 1 Chapter-5.
Virtual techdays INDIA │ Nov 2010 Developing Office Biz Application using WPF on Windows 7 Sarang Datye │ Sr. Consultant, Microsoft Sridhar Poduri.
LiveCycle Data Services Introduction Part 2. Part 2? This is the second in our series on LiveCycle Data Services. If you missed our first presentation,
Tutorial 121 Creating a New Web Forms Page You will find that creating Web Forms is similar to creating traditional Windows applications in Visual Basic.
Windows Presentation Foundation Adam Calderon Principal Engineer Interknowlogy LLC
11 Web Services. 22 Objectives You will be able to Say what a web service is. Write and deploy a simple web service. Test a simple web service. Write.
ASP.NET.. ASP.NET Environment ASP.NET is Microsoft's programming framework that enables the development of Web applications and services. It is an easy.
Chapter One An Introduction to Visual Basic 2010 Programming with Microsoft Visual Basic th Edition.
Sample Application Multi Layered Architecture (n-tier): –Graphical User Interface (GUI): Forms, components, controls The Visual Designer in Visual Studio.
Copyright ©2004 Virtusa Corporation | CONFIDENTIAL Windows Presentation Foundation Ruwan Wijesinghe.
Office Business Applications Workshop Defining Business Process and Workflows.
Visual C# 2012 How to Program © by Pearson Education, Inc. All Rights Reserved.
Windows Presentation Foundation (WPF). Introduction Separates appearance of user interface from behavior Appearance usually specified by XAML Behavior.
Copyright ©2004 Virtusa Corporation | CONFIDENTIAL Windows Workflow Foundation Ruwan Wijesinghe.
Visual C# 2012 How to Program © by Pearson Education, Inc. All Rights Reserved.
Module 14 Application Settings, State, and Life Cycle.
Windows 10 UWP MVVM In Depth
Slide 1. Agenda  Introduction to Windows Workflow What is it? What are activities? Hosting  Out of the box Activities  Custom Activities and Dependency.
Architecture Multi Layered Architecture (n-tier): Application: Model Controllers Database Access Graphical User Interface (GUI): Forms, components, controls.
1 Java Server Pages A Java Server Page is a file consisting of HTML or XML markup into which special tags and code blocks are inserted When the page is.
Chapter 27 Getting “Web-ified” (Web Applications) Clearly Visual Basic: Programming with Visual Basic nd Edition.
Building Custom Controls with ASP.NET and the Microsoft ®.NET Framework Rames Gantanant Microsoft Regional Director, Thailand
Copyright ©2004 Virtusa Corporation | CONFIDENTIAL Windows Presentation Foundation Ruwan Wijesinghe.
WPF (Avalon), Windows App GUI Windows App GUI Web App GUI Web App GUI HTML HTML XML XML WPF WPF LINQ LINQ.
METADATA IN.NET Presented By Sukumar Manduva. INTRODUCTION  What is Metadata ? Metadata is a binary information which contains the complete description.
Part of the Microsoft.NET Framework 3.0 Tomer Shamam.NET Technologies Expert Sela Group
Windows Communication Foundation and Web Services
Dive Into® Visual Basic 2010 Express
Computing with C# and the .NET Framework
ASP.NET Forms.
IS 350 Application Structure
Important New Concepts In WPF
Chapter 1: An Introduction to Visual Basic 2015
Data Virtualization Tutorial… CORS and CIS
Chapter 3: Using Methods, Classes, and Objects
Chapter Eleven Handling Events.
Using GUI Objects and the Visual Studio IDE
Indexer AKEEL AHMED.
XAML User Interface Creation in C#
Microsoft Access Illustrated
Social Media And Global Computing Introduction to Visual Studio
Resources & Controls AKEEL AHMED.
Java applets 1/3/2019.
Lecture Set 11 Creating and Using Classes
Tonga Institute of Higher Education
ASP.NET.
Web Development Using ASP .NET
Pre-assessment Questions
Presentation transcript:

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. Application-level services are navigation, resources, configuration and hosting

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.

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>

Scalable Applications (Contd..)

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>

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

Scalable Applications (Contd..) App.xaml <Application xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' StartupUri='helloworld.xaml' />

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> </Project>

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

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> </Project>

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

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>

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>

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>

Web Style (contd..) The output…

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.

Desktop style (contd..)

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.

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

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.

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

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

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.

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

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>

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

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.

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

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

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.

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.

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'");

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

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; ...

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;

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.

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.

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

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.

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;

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

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.

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

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.

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

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.

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>

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

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.

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.

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>

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

User Controls (contd..)

Navigation and Pages Logical model for navigation

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

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

Navigation and Pages (contd..)

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>

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>

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

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

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

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

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

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

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);

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);

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));

References Essential Windows Presentation Foundation by Chris Anderson