Top Banner
Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic
112

Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

Sep 26, 2018

Download

Documents

trinhliem
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

Object Innovations Course 4235

Student Guide Revision 2.0

Windows Presentation Foundation

Using Visual Basic

Page 2: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

Rev. 2.0 Copyright ©2008 Object Innovations Enterprises, LLC ii All Rights Reserved

Windows Presentation Foundation Using Visual Basic Rev. 2.0 Student Guide Information in this document is subject to change without notice. Companies, names and data used in examples herein are fictitious unless otherwise noted. No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without the express written permission of Object Innovations. Product and company names mentioned herein are the trademarks or registered trademarks of their respective owners. Authors: Robert J. Oberg and Ernani Junior Cecon Special Thanks: Dana Wyatt Copyright ©2008 Object Innovations Enterprises, LLC All rights reserved. Object Innovations 877-558-7246 www.objectinnovations.com Published in the United States of America.

Page 3: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

Rev. 2.0 Copyright ©2008 Object Innovations Enterprises, LLC iii All Rights Reserved

Table of Contents (Overview) Chapter 1 Introduction to WPF Chapter 2 XAML Chapter 3 WPF Controls Chapter 4 Layout Chapter 5 Dialogs Chapter 6 Menus and Commands Chapter 7 Toolbars and Status Bars Chapter 8 Dependency Properties and Routed Events Chapter 9 Resources Chapter 10 Data Binding Chapter 11 Styles, Templates, Skins and Themes Appendix A Learning Resources

Page 4: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

Rev. 2.0 Copyright ©2008 Object Innovations Enterprises, LLC iv All Rights Reserved

Directory Structure

• Install the course software by running the self-extractor Install_WpfVb_20.exe.

• The course software installs to the root directory c:\OIC\WpfVb.

− Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02 and so on.

− The Labs directory contains one subdirectory for each lab, named after the lab number. Starter code is frequently supplied, and answers are provided in the chapter directories.

− The Demos directory is provided for performing in-class demonstrations led by the instructor.

• Data files install to the directory c:\OIC\Data.

Page 5: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

Rev. 2.0 Copyright ©2008 Object Innovations Enterprises, LLC v All Rights Reserved

Table of Contents (Detailed)

Chapter 1: Introduction to WPF......................................................................................... 1 History of Microsoft GUI ................................................................................................... 3 Why WPF?.......................................................................................................................... 4 When Should I Use WPF? .................................................................................................. 5 WPF and .NET Framework 3.0 .......................................................................................... 6 .NET Framework 3.5 .......................................................................................................... 7 Visual Studio 2008.............................................................................................................. 8 Visual Studio 2008 Versions .............................................................................................. 9 WPF Core Types and Infrastructures................................................................................ 10 XAML............................................................................................................................... 11 Controls............................................................................................................................. 12 Data Binding ..................................................................................................................... 13 Appearance ....................................................................................................................... 14 Layout and Panels ............................................................................................................. 15 Graphics ............................................................................................................................ 16 Media ................................................................................................................................ 17 Documents and Printing.................................................................................................... 18 Plan of Course................................................................................................................... 19 Application and Window .................................................................................................. 20 References and Imports..................................................................................................... 21 FirstWpf Example Program .............................................................................................. 22 Demo – Using Visual Studio 2008 ................................................................................... 23 Creating a Button .............................................................................................................. 24 Providing an Event Handler.............................................................................................. 25 Specifying Initial Input Focus........................................................................................... 26 Complete First Program.................................................................................................... 27 Device-Independent Pixels ............................................................................................... 28 Class Hierarchy................................................................................................................. 29 Content Property ............................................................................................................... 30 Simple Brushes ................................................................................................................. 31 Panels ................................................................................................................................ 32 Children of Panels............................................................................................................. 33 Example – TwoControls ................................................................................................... 34 TwoControls – Code ......................................................................................................... 35 Automatic Sizing .............................................................................................................. 36 Lab 1 ................................................................................................................................. 38 Summary ........................................................................................................................... 39

Chapter 2: XAML............................................................................................................... 43 What Is XAML? ............................................................................................................... 45 Default Namespace ........................................................................................................... 46 XAML Language Namespace........................................................................................... 47

Page 6: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

Rev. 2.0 Copyright ©2008 Object Innovations Enterprises, LLC vi All Rights Reserved

Elements and Attributes.................................................................................................... 48 XAML in Visual Studio 2008........................................................................................... 49 Demo: One Button via XAML ......................................................................................... 50 Layout in WPF.................................................................................................................. 55 Controlling Size ................................................................................................................ 56 Margin and Padding.......................................................................................................... 57 Thickness Structure........................................................................................................... 58 Children of Panels............................................................................................................. 59 Example – TwoControlsXaml .......................................................................................... 60 TwoControls – XAML...................................................................................................... 61 Automatic Sizing .............................................................................................................. 62 TwoControls – Code ......................................................................................................... 63 Orientation ........................................................................................................................ 64 Access Keys ...................................................................................................................... 65 Access Keys in XAML ..................................................................................................... 66 Content Property ............................................................................................................... 67 Checked and Unchecked Events....................................................................................... 68 Lab 2 ................................................................................................................................. 69 Property Element Syntax .................................................................................................. 70 Type Converters................................................................................................................ 71 Summary ........................................................................................................................... 72

Chapter 3: WPF Controls .................................................................................................. 79 Buttons in WPF................................................................................................................. 81 ButtonDemo Example....................................................................................................... 82 Using the Button Class ..................................................................................................... 83 Toggle Buttons.................................................................................................................. 84 IsThreeState ...................................................................................................................... 85 CheckBox.......................................................................................................................... 86 CheckBox Code ................................................................................................................ 87 ToolTip ............................................................................................................................. 88 RadioButton ...................................................................................................................... 89 GroupBox.......................................................................................................................... 90 Images ............................................................................................................................... 91 Lab 3A .............................................................................................................................. 92 TextBox............................................................................................................................. 93 Initializing the TextBox .................................................................................................... 94 Clipboard Support............................................................................................................. 95 Items Controls................................................................................................................... 96 Selector Controls............................................................................................................... 97 Using a ListBox ................................................................................................................ 98 ShowListSingle Example.................................................................................................. 99 Multiple-Selection ListBox............................................................................................. 100 Selected Items ................................................................................................................. 101 Using the ComboBox...................................................................................................... 102 ComboBox Example....................................................................................................... 103

Page 7: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

Rev. 2.0 Copyright ©2008 Object Innovations Enterprises, LLC vii All Rights Reserved

Storing Objects in List Controls ..................................................................................... 105 Collection Items in XAML ............................................................................................. 106 Lab 3B............................................................................................................................. 107 Summary ......................................................................................................................... 108

Chapter 4: Layout............................................................................................................. 117 Layout in WPF................................................................................................................ 119 Controlling Size: Review................................................................................................ 120 Margin and Padding: Review ......................................................................................... 121 Thickness Structure: Review .......................................................................................... 122 SizeDemo Program ......................................................................................................... 123 Top Panel ........................................................................................................................ 124 Content Property ............................................................................................................. 125 XAML vs. Code.............................................................................................................. 126 Type Converter ............................................................................................................... 128 Fixed vs. Dynamic Sizing ............................................................................................... 129 Specifying Font Size ....................................................................................................... 130 Alignment ....................................................................................................................... 131 Default Alignment Example ........................................................................................... 132 Alignment inside a Stack Panel ...................................................................................... 133 Vertical Alignment ......................................................................................................... 134 Horizontal Alignment ..................................................................................................... 135 Vertical Alignment in a Window.................................................................................... 136 Content Alignment.......................................................................................................... 137 Content Alignment Example........................................................................................... 138 FlowDirection ................................................................................................................. 139 Transforms ...................................................................................................................... 140 RotateTransform Example .............................................................................................. 141 Panels .............................................................................................................................. 142 Shapes ............................................................................................................................. 143 Size and Position............................................................................................................. 144 Simple Shapes Example.................................................................................................. 145 Attached Properties......................................................................................................... 146 StackPanel....................................................................................................................... 147 Children of StackPanel ................................................................................................... 148 WrapPanel....................................................................................................................... 149 DockPanel ....................................................................................................................... 150 Dock Example XAML and Code.................................................................................... 151 Lab 4A ............................................................................................................................ 152 Grid ................................................................................................................................. 153 Grid Example .................................................................................................................. 154 Grid Demo ...................................................................................................................... 155 Star Sizing....................................................................................................................... 156 Grid.ColumnSpan ........................................................................................................... 157 Scrolling.......................................................................................................................... 158 Scaling ............................................................................................................................ 159

Page 8: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

Rev. 2.0 Copyright ©2008 Object Innovations Enterprises, LLC viii All Rights Reserved

Lab 4B............................................................................................................................. 160 Summary ......................................................................................................................... 161

Chapter 5: Dialogs ............................................................................................................ 179 Dialog Boxes in WPF ..................................................................................................... 181 MessageBox.................................................................................................................... 182 MessageBox Show Method ............................................................................................ 183 Closing a Form: Review ................................................................................................. 186 Common Dialog Boxes................................................................................................... 187 FileOpen Example .......................................................................................................... 188 FileOpen Example Code ................................................................................................. 189 Custom Dialogs............................................................................................................... 190 Modal Dialogs................................................................................................................. 191 Modal Dialog Example ................................................................................................... 192 New Product Dialog........................................................................................................ 193 XAML for New Product Dialog ..................................................................................... 194 Code for New Product Dialog......................................................................................... 195 Bringing up the Dialog ................................................................................................... 196 Dialog Box Owner .......................................................................................................... 197 Modeless Dialog Box Example ...................................................................................... 198 Displaying the Dialog ..................................................................................................... 199 XAML for Modeless Dialog........................................................................................... 200 Handler for the Apply Button ......................................................................................... 201 Handler for the Close Button .......................................................................................... 202 Instances of a Modeless Dialog ...................................................................................... 203 Checking for an Instance ................................................................................................ 204 Lab 5 ............................................................................................................................... 205 Summary ......................................................................................................................... 206

Chapter 6: Menus and Commands ................................................................................. 213 Menus in WPF ................................................................................................................ 215 Menu Controls ................................................................................................................ 216 MenuCalculator Example ............................................................................................... 217 A Simple Menu ............................................................................................................... 218 The Menu Using XAML................................................................................................. 219 Handling the Click Event................................................................................................ 220 The Menu Using Procedural Code.................................................................................. 221 Icons in Menus................................................................................................................ 222 Context Menu ................................................................................................................. 223 XAML for Context Menu ............................................................................................... 224 Separator ......................................................................................................................... 225 Lab 6A ............................................................................................................................ 226 Keyboard Shortcuts......................................................................................................... 227 Commands ...................................................................................................................... 228 Simple Command Demo................................................................................................. 229 WPF Command Architecture.......................................................................................... 232

Page 9: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

Rev. 2.0 Copyright ©2008 Object Innovations Enterprises, LLC ix All Rights Reserved

Command Bindings ........................................................................................................ 233 Command Binding Demo ............................................................................................... 234 Custom Commands ......................................................................................................... 237 Custom Command Example ........................................................................................... 238 MenuCalculator Command Bindings ............................................................................. 240 Input Bindings................................................................................................................. 241 Menu Items ..................................................................................................................... 242 Running MenuCalculator................................................................................................ 243 Checking Menu Items ..................................................................................................... 244 Common Event Handlers ................................................................................................ 245 Menu Checking Logic .................................................................................................... 246 Calculation Logic............................................................................................................ 247 Automatic Checking ....................................................................................................... 248 Automatic Checking Example ........................................................................................ 249 Lab 6B............................................................................................................................. 250 Summary ......................................................................................................................... 251

Chapter 7: Toolbars and Status Bars ............................................................................. 259 Toolbars in WPF............................................................................................................. 261 XAML for Toolbars........................................................................................................ 262 Commands and Events.................................................................................................... 263 Images on Buttons........................................................................................................... 264 Tool Tips......................................................................................................................... 265 Other Elements on Toolbars ........................................................................................... 266 Status Bars ...................................................................................................................... 267 Lab 7 ............................................................................................................................... 268 Summary ......................................................................................................................... 269

Chapter 8: Dependency Properties and Routed Events................................................ 277 Dependency Properties ................................................................................................... 279 Change Notification........................................................................................................ 280 Property Trigger Example .............................................................................................. 281 Property Value Inheritance ............................................................................................. 282 Property Value Inheritance Example.............................................................................. 283 Support for Multiple Providers ....................................................................................... 284 Logical Trees .................................................................................................................. 285 Visual Trees .................................................................................................................... 286 Visual Tree Example....................................................................................................... 287 Routed Events ................................................................................................................. 288 Event Handlers................................................................................................................ 289 Routing Strategies........................................................................................................... 290 Ready-made Routed Events in WPF............................................................................... 291 Routed Event Example ................................................................................................... 292 Lab 8 ............................................................................................................................... 295 Summary ......................................................................................................................... 296

Page 10: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

Rev. 2.0 Copyright ©2008 Object Innovations Enterprises, LLC x All Rights Reserved

Chapter 9: Resources........................................................................................................ 301 Resources in .NET .......................................................................................................... 303 Resources in WPF........................................................................................................... 304 Binary Resources ............................................................................................................ 305 Loose Files as Resources ................................................................................................ 306 Binary Resources Example ............................................................................................. 307 Logical Resources........................................................................................................... 308 Logical Resources Demo ................................................................................................ 310 Logical Resources in Code ............................................................................................. 313 Static Resources .............................................................................................................. 315 Dynamic Resources ........................................................................................................ 316 DynamicResource Example............................................................................................ 317 Lab 9 ............................................................................................................................... 318 Summary ......................................................................................................................... 319

Chapter 10: Data Binding ................................................................................................ 325 What is Data Binding? .................................................................................................... 327 Binding in Procedural Code............................................................................................ 328 Procedural Code Example............................................................................................... 329 Binding in XAML........................................................................................................... 331 Binding to Plain .NET Properties ................................................................................... 332 Binding to .NET Properties Example ............................................................................. 333 Binding to a Collection ................................................................................................... 335 Binding to a Collection Example.................................................................................... 336 Lab 10A .......................................................................................................................... 337 Controlling the Selected Item ......................................................................................... 338 ComboBox Synchronization Example............................................................................ 339 Data Context ................................................................................................................... 340 Data Context Demo......................................................................................................... 341 Data Templates ............................................................................................................... 344 Data Template Example.................................................................................................. 345 Specifying a Data Template............................................................................................ 346 Value Converters ............................................................................................................ 347 Value Converter Example............................................................................................... 348 Using a Value Converter in XAML................................................................................ 349 Collection Views............................................................................................................. 351 Sorting............................................................................................................................. 352 Grouping ......................................................................................................................... 353 Grouping Example .......................................................................................................... 354 Filtering........................................................................................................................... 356 Filtering Example ........................................................................................................... 357 Collection Views in XAML............................................................................................ 358 Collection Views in XAML Example............................................................................. 359 Data Providers................................................................................................................. 360 ObjectDataProvider ........................................................................................................ 361 ObjectDataProvider Example ......................................................................................... 362

Page 11: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

Rev. 2.0 Copyright ©2008 Object Innovations Enterprises, LLC xi All Rights Reserved

XmlDataProvider ............................................................................................................ 364 XmlDataProvider Example............................................................................................. 365 Lab 10B........................................................................................................................... 366 Summary ......................................................................................................................... 367

Chapter 11: Styles, Templates, Skins and Themes ........................................................ 379 WPF and Interfaces......................................................................................................... 381 Styles............................................................................................................................... 382 Style Example ................................................................................................................. 383 Style Definition............................................................................................................... 384 Applying Styles............................................................................................................... 385 Style Inheritance ............................................................................................................. 386 Style Overriding.............................................................................................................. 387 Sharing Styles ................................................................................................................. 388 Style Sharing Example.................................................................................................... 389 Demo: Restricting Styles ................................................................................................ 391 Typed Styles ................................................................................................................... 394 Typed Style Example...................................................................................................... 395 Triggers ........................................................................................................................... 397 Property Trigger Example .............................................................................................. 398 Data Trigger Example..................................................................................................... 399 Multiple Conditions ........................................................................................................ 401 Validation........................................................................................................................ 402 Validation Example ........................................................................................................ 403 Templates........................................................................................................................ 404 A Simple Template Example .......................................................................................... 405 Improving the Template.................................................................................................. 406 Templated Parent’s Properties ........................................................................................ 407 Respecting Properties Example ...................................................................................... 408 Respecting Visual States................................................................................................. 411 Respecting Visual States Example ................................................................................. 412 Using Templates with Styles .......................................................................................... 413 Templates with Styles Example...................................................................................... 414 Skins................................................................................................................................ 415 Changing Skins ............................................................................................................... 416 Skins Example ................................................................................................................ 417 Themes............................................................................................................................ 419 Themes Example............................................................................................................. 420 Lab 11 ............................................................................................................................. 422 Summary ......................................................................................................................... 423

Appendix A: Learning Resources.................................................................................... 437

Page 12: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

Rev. 2.0 Copyright ©2008 Object Innovations Enterprises, LLC xii All Rights Reserved

Page 13: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 1 All Rights Reserved

Chapter 1

Introduction to WPF

Page 14: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 2 All Rights Reserved

Introduction to WPF

Objectives

After completing this unit you will be able to:

• Discuss the rationale for WPF.

• Describe what WPF is and its position in the .NET Framework 3.5.

• Give an overview of the main features of WPF.

• Describe the role of the fundamental Application and Window classes.

• Implement a “Hello, World” Windows application using WPF.

• Create, build and run simple WPF programs using Visual Studio 2008.

• Use simple brushes in your WPF programs.

• Use panels to lay out Windows that have multiple controls.

Page 15: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 3 All Rights Reserved

History of Microsoft GUI

• WPF is an extremely sophisticated and complex technology for creating GUI programs.

• Why has Microsoft done this when Windows Forms and Web Forms in .NET are so new themselves?

• To understand let’s take a look back at various technologies Microsoft has employed over the years to support GUI application development:

− Windows 1.0 was the first GUI environment from Microsoft (ignoring OS/2, which is no longer relevant), provided as a layer on top of DOS, relying on the GDI and USER subsystems for graphics and user interface.

− Windows has gone through many versions, but always using GDI and USER, which have been enhanced over the years.

− DirectX was introduced in 1995 as a high-performance graphics system, targeting games and other graphics-intensive environments.

− Windows Forms in .NET used a new enhanced graphics subsystem, GDI+.

− DirectX has gone through various versions, with DirectX 9 providing a library to use with managed .NET code,

Page 16: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 4 All Rights Reserved

Why WPF?

• The various technologies support development of sophisticated graphics and GUI programs, but there are several different, complex technologies a programmer may need to know.

• The goal of Windows Presentation Framework is to provide a unified framework for creating modern user experiences.

− It is built on top of .NET, providing all the productivity benefits of the large .NET class library.

• Benefits of WPF include:

− Integration of 2D and 3D graphics, video, speech, and rich document viewing.

− Resolution independence, spanning mobile devices and 50 inch televisions.

− Easy use of hardware acceleration when available.

− Declarative programming of objects in the WPF library through a new Extensible Application Markup Language, or XAML.

− Easy deployment through Windows Installer, ClickOnce, or by hosting in a Web browser.

Page 17: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 5 All Rights Reserved

When Should I Use WPF?

• DirectX can still provide higher graphics performance and can exploit new hardware features before they are exposed through WPF.

− But DirectX is a low-level interface and much harder to use than WPF.

• WPF is better than Windows Forms for applications with rich media, but what about business applications with less demanding graphics environments?

− Initially, WPF lacks some Windows Forms controls.

− But future development at Microsoft will be focused on WPF rather than Windows Forms, so the long range answer is clearly to migrate to WPF development.

− Visual Studio 2008 provides strong tool support for WPF.

• Is WPF a replacement for Adobe “Flash” for Web applications with a rich user experience?

− Viewing rich WPF Web content requires Windows and .NET Framework 3.0 or 3.5, default for Windows Vista but not for other Windows operating systems.

− Microsoft Silverlight is a new product that is a small lightweight subset of the WPF runtime. It may attain ubiquitous browser support.

− Time will tell!

Page 18: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 6 All Rights Reserved

WPF and .NET Framework 3.0

• WPF is a component of a group of new .NET technologies, formerly called WinFX and now called .NET Framework 3.0.

• It layers on top of .NET Framework 2.0.

• WPF provides a unified programming model for creating rich user experiences incorporating UI, media and documents.

Page 19: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 7 All Rights Reserved

.NET Framework 3.5

• The .NET Framework 3.5 adds a number of important features beyond those of .NET 3.0.

− Perhaps the most important is integration with the tooling support provided by Visual Studio 2008, which we’ll discuss later in the chapter.

• Language Integrated Query (LINQ) extends query capabilities to the syntax of the C# and Visual Basic programming languages.

− The technology can be extended to almost any data store, and out of the box includes support for objects, the file system, SQL Server and XML.

• Enhancements to the C# programming language, largely to support LINQ.

• Integration of ASP.NET AJAX into the .NET Framework.

• Many other enhancements, including:

− A powerful Add-In infrastructure

− Peer-to-peer networking support

− Integration of WCF and WF

− Enhancements to both WPF and Windows Forms

− Enhancements to ASP.NET, including new controls and a Web Application project.

Page 20: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 8 All Rights Reserved

Visual Studio 2008

• Visual Studio 2008 provides effective tooling support for .NET Framework 3.5.

− Although .NET 3.0 add-ins for Visual Studio 2005 were available, full tool support only comes with Visual Studio 2008.

• Enhancements in Visual Studio 2008 include:

− Improvements in the Integrated Development Environment (IDE), such as better navigation and easier docking.

− Automatic settings migration from Visual Studio 2005 (but third-party add-ons must be manually migrated).

− Multi-targeting to .NET 2.0, .NET 3.0 or .NET 3.5.

• There are many new project templates, including:

− WPF projects

− WCF projects

− WF projects

− Reporting projects

• There are a number of new designers, including WPF Designer, an object/relational designer, and a workflow designer.

Page 21: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 9 All Rights Reserved

Visual Studio 2008 Versions

• The Express Editions provides a lightweight IDE, with separate versions for C#, Visual Basic, Visual C++, and for Web application development.

− These versions provide a simplified environment and are permanently free.

• Visual Studio 2008 Standard Edition provides a fully integrated environment for all the supported languages and project types.

− Numerous additional features are provided for debugging, refactoring, XML programming, WCF development, and other tasks.

− It provides most of the features of the Professional Edition at a lower price point.

− Everything covered in this course works fine with the Standard Edition.

− Visual Studio 2008 Professional Edition supports development for a wider range of platforms, including Microsoft Office, smart devices, and Windows CE.

− It also includes automated support for unit testing.

Page 22: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 10 All Rights Reserved

WPF Core Types and Infrastructures

• A great many classes in WPF inherit from one of four different classes:

− UIElement

− FrameworkElement

− ContentElement

− FrameworkContentElement

• These classes, often called base element classes, provide the foundation for a model of composing user interfaces.

• WPF user interfaces are composed of elements that are assembled in a tree hierarchy, known as an element tree.

• The element tree is both an intuitive way to lay out user interfaces and a structure over which you can layer powerful UI services.

− The dependency property system enables one element to implement a property that is automatically shared by elements lower in the element tree hierarchy.

− Routed events can route events along the element tree, affording event handlers all along the traversed path to handle the event.

Page 23: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 11 All Rights Reserved

XAML

• Extensible Application Markup Language (XAML, pronounced “zammel”) provides a declarative way to define user interfaces.

• Here is the XAML definition of a simple button. <Button FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center" > Say Hello </Button>

• To see this button displayed, we’ll need some more program elements, which we’ll discuss later.

• XAML has many advantages, and we’ll study it beginning in the next chapter.

− Using XAML facilitates separating front-end appearance from back-end logic.

− XAML is the most concise way to represent user interfaces.

− XAML is defined to work well with tools.

Page 24: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 12 All Rights Reserved

Controls

• WPF comes with many useful controls, and more should come as the framework evolves:

− Editing controls such as TextBox, CheckBox, RadioButton.

− List controls such as ListBox, ListView, TreeView.

− User information such as Label, ProgressBar, ToolTip.

− Action such as Button, Menu and ToolBar.

− Appearance such as Border, Image and Viewbox.

− Common dialog boxes such as OpenFileDialog and PrintDialog.

− Containers such as GroupBox, ScrollBar and TabControl.

− Layout such as StackPanel, DockPanel and Grid.

− Navigation such as Frame and Hyperlink.

− Documents such as DocumentViewer.

• The appearance of controls can be customized without programming with styles and templates.

• If necessary, you can create a custom control by deriving a new class from an appropriate base class.

Page 25: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 13 All Rights Reserved

Data Binding

• WPF applications can work with many different kinds of data:

− Simple objects

− Collection objects

− WPF elements

− ADO.NET data objects

− XML objects

− Objects returned from Web services

• WPF provides a data binding mechanism that binds these different kinds of data to user interface elements in your application.

− Data binding can be implemented both in code and also declaratively using XAML.

Page 26: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 14 All Rights Reserved

Appearance

• WPF provides extensive facilities for customizing the appearance of your application.

• UI resources allow you to define objects and values once, for things like fonts, background colors, and so on, and reuse them many times.

• Styles enable a UI designer to standardize on a particular look for a whole product.

• Control templates enable you to replace the default appearance of a control while retaining its default behavior.

• With data templates, you can control the default visualization of bound data.

• With themes, you can package common looks that are applied throughout an application.

Page 27: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 15 All Rights Reserved

Layout and Panels

• Layout is the proper sizing and positioning of controls as part of the process of composing the presentation for the user.

• The WPF layout system both simplifies the layout process through useful classes and provides adaptability of the UI appearance in the face of changes:

− Window resizing

− Screen resolution and dots per inch

• The layout infrastructure is provided by a number of classes:

− StackPanel

− DockPanel

− WrapPanel

− Grid

− Canvas

• The flexible layout system of WPF facilitates globalization of user interfaces.

Page 28: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 16 All Rights Reserved

Graphics

• WPF provides an improved graphics system.

• Resolution and device-independent graphics: WPF uses device-independent units, enabling resolution and device independence.

− Each pixel, which is device-independent, automatically scales with the dots-per-inch setting of your system.

• Improved precision: WPF uses double in place of float and provides support for a wider array of colors.

• Advanced graphics and animation support.

− You can use animation to make controls and elements grow, spin, and fade, and so on. You create interesting page transitions, and other special effects.

• Hardware acceleration: The WPF graphics engine is designed to take advantage of graphics hardware where available.

Page 29: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 17 All Rights Reserved

Media

• WPF provides rich support for media, including images, video and audio.

• WPF enables you to work with images in a variety of ways. Images include:

− Icons

− Backgrounds

− Parts of animations

• WPF provides native support for both video and audio.

− The MediaElement control makes it easy to play both video and audio.

Page 30: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 18 All Rights Reserved

Documents and Printing

• WPF provides improved support in working with text and typography.

• WPF includes support for three different types of documents:

− Fixed documents support a precise WYSIWYG presentation.

− Flow documents dynamically adjust and reflow their content based on run-time variables like window size and device resolution.

− XPS documents (XPS Paper Specification) is a paginated representation of electronic paper described in an XML-based format. XPS is an open and cross-platform document format.

• WPF provides better control over the print system, including remote printing and queues.

− XPS documents can be printed directly without conversion into a print format such as Enhanced Metafile (EMF), Printer Control Language (PCL) or PostScript.

• WPF provides a framework for annotations, including “Sticky Notes.”

Page 31: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 19 All Rights Reserved

Plan of Course

• As you can see, Windows Presentation Foundation is a large, complex technology.

• In a short course such as this one, the most we can do is to provide you with an effective orientation to this large landscape.

• We provide a step-by-step elaboration of the most fundamental features of WPF and many small, complete example programs.

• We follow this sequence:

− In the rest of this chapter we introduce you to several, small “Hello, World” sample WPF applications.

− The second chapter introduces XAML.

− The third chapter covers a number of simple WPF controls.

− We discuss layout in more detail.

− We then cover common user interface features in Windows programming, including dialogs, menus and toolbars.

− The course concludes with resources and dependency properties.

Page 32: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 20 All Rights Reserved

Application and Window

• The two most fundamental classes in WPF are Application and Window.

− A WPF application usually starts out by creates objects of type Application and Window.

− For an example, see the file Program.vb in the folder FirstWpf\Step1 in the chapter directory for Chapter 1.

Namespace FirstWpf Public Class MainWindow Inherits Window <STAThread()> _ Shared Sub Main(ByVal args() As String) Dim app As New Application() app.Run(New MainWindow()) End Sub Public Sub New() Title = "Welcome to WPF (Code)" Width = 288 Height = 192 End Sub End Class End Namespace

• A program can create only one Application object, which is invisible. A Window object is visible, corresponding to a real window.

Page 33: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 21 All Rights Reserved

References and Imports

• A Visual Basic WPF Application project template automatically provides important WPF references:

− PresentationCore

− PresentationFramework

− WindowsBase

• Important imports are also provided:

− System.Windows

− System.Windows.Controls

Page 34: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 22 All Rights Reserved

FirstWpf Example Program

• Our example program has the following features:

− Bring in the System.Windows namespace. This namespace includes the fundamental WPF classes, interfaces, delegates, and so on, including the classes Application and Window.

− Make your class derive from the Window class.

− Provide the attribute <STAThread> in front of the Main() method. This is required in WPF and ensures interoperability with COM.

− In Main(), instantiate an Application object and call the Run() method.

− In the call to Run() pass a new instance of your Window-derived class.

− In the constructor of your Window-derived class, specify any desired properties of your Window object. We set the Title, Width and Height.

• Build and run. You’ll see:

Page 35: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 23 All Rights Reserved

Demo – Using Visual Studio 2008

• Although you can compile WPF programs at the command-line, for simplicity we will use Visual Studio 2008 throughout this course.

− To make clear all the details in creating a WPF application, we’ll create our sample program from scratch in the Demos directory.

1. Use the New Project dialog to create a new WPF Application called FirstWpf in the Demos directory.

2. In Solution Explorer, delete the files App.xaml and Window1.xaml.

3. Add a new code file Program.vb to your project.

4. Enter the code shown two pages back. If you like, to save typing, you may copy/paste from the FirstWpf\Step1 folder.

5. Build and run. You are now at Step 1. That’s all there is to creating a simple WPF program using Visual Studio 2008!

Page 36: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 24 All Rights Reserved

Creating a Button

6. Continuing the demo, let’s add a button to our main window. Begin with the following code addition.

Public Sub New() Title = "Welcome to WPF (Code)" Width = 288 Height = 192 Dim btn As New Button() btn.Content = "Say Hello" btn.FontSize = 16 Content = btn End Sub 7. Build and run. You’ll se the button fills the whole client area of

the main window.

8. Add the following code to specify the horizontal and vertical alignment of the button.

btn.HorizontalAlignment = HorizontalAlignment.Center btn.VerticalAlignment = VerticalAlignment.Center 9. Build and run. Now the button will be properly displayed, sized

just large enough to contain the button’s text in the designated font.

Page 37: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 25 All Rights Reserved

Providing an Event Handler

10. Continuing the demo, add the following code to specify an event handler for clicking the button.

... AddHandler btn.Click, AddressOf ButtonOnClick Content = btn End Sub Private Sub ButtonOnClick(ByVal sender As Object, _ ByVal args As RoutedEventArgs) MessageBox.Show("Hello, WPF", "Greeting") End Sub 11. Build and run. You will now see a message box displayed

when you click the “Say Hello” button

Page 38: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 26 All Rights Reserved

Specifying Initial Input Focus

12. You can specify the initial input focus by calling the Focus() method of the Button class (inherited from the UIElement class).

btn.Focus() 13. Build and run. The button will now have the initial input

focus, and hitting the Enter key will invoke the button’s Click event handler. You are now at Step 2.

• Note that specifying the focus programmatically in this manner is deprecated, because it violates accessibility guidelines.

− When run for the visually impaired, setting the focus will cause the text of the button to be read out.

Page 39: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 27 All Rights Reserved

Complete First Program

• See FirstWpf\Step2. Public Class MainWindow Inherits Window <STAThread()> _ Shared Sub Main(ByVal args() As String) Dim app As New Application() app.Run(New MainWindow()) End Sub Public Sub New() Title = "Welcome to WPF (Code)" Width = 288 Height = 192 Dim btn As New Button() btn.Content = "Say Hello" btn.FontSize = 16 btn.HorizontalAlignment = _ HorizontalAlignment.Center btn.VerticalAlignment = _ VerticalAlignment.Center AddHandler btn.Click, AddressOf ButtonOnClick ' Setting focus is deprecated for ' violating accessibility guidelines btn.Focus() Content = btn End Sub Private Sub ButtonOnClick(ByVal sender As _ Object, ByVal args As RoutedEventArgs) MessageBox.Show("Hello, WPF", "Greeting") End Sub End Class

Page 40: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 28 All Rights Reserved

Device-Independent Pixels

• The Width and Height properties for the main window are specified in device-independent pixels (or units).

− Each such unit is 1/96 inch.

− Values of 288 and 192 thus represent a window that is 3 inches by 2 inches.

• If you get a new monitor with a much higher resolution, the window will still be displayed with a size of 3 inches by 2 inches.

• Note that this mapping to inches assumes that your monitor is set to its “natural” resolution.

− Any differences will be reflected in a different physical size.

Page 41: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 29 All Rights Reserved

Class Hierarchy

• The key classes Application, Window and Button all derive from the abstract class DispatcherObject.

Object DispatcherObject (abstract) Application DependencyObject Visual (abstract) UIElement FrameworkElement Control ContentControl Window ButtonBase Button

Page 42: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 30 All Rights Reserved

Content Property

• The key property of Window is Content.

− The Content property also applies to all controls that derive from ContentControl, including Button.

• You can set Content to any one object.

− This object can be anything, such as a string, a bitmap, or any control.

− In our example program, we set the Content of the main window to the Button that we created.

Dim btn As New Button() ... Content = btn

• We will see a little later how we can overcome the limitation of one object to create a window that has multiple controls in it.

Page 43: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 31 All Rights Reserved

Simple Brushes

• You may specify a foreground or background of a window or control by means of a Brush.

− We will look at the simplest brush class, SolidColorBrush.

• You can specify a color for a SolidColorBrush in a couple of ways:

− By using the Colors enumeration.

− By using the FromRgb() method of the Color class.

• The program SimpleBrush illustrates setting foreground and background properties.

Public Sub New() Title = "Simple Brushes" Width = 288 Height = 192 Background = New SolidColorBrush(Colors.Beige) Dim btn As New Button() btn.Content = "Say Hello" btn.FontSize = 16 btn.HorizontalAlignment = _ HorizontalAlignment.Center btn.VerticalAlignment = VerticalAlignment.Center AddHandler btn.Click, AddressOf ButtonOnClick btn.Background = _ New SolidColorBrush(Color.FromRgb(0, 255, 0)) btn.Foreground = _ New SolidColorBrush(Color.FromRgb(0, 0, 255)) Content = btn End Sub

Page 44: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 32 All Rights Reserved

Panels

• As we have seen, the Content of a window can be set only to a single object.

• What do we do if we want to place multiple controls on a window?

• We use a Panel, which is a single object and can have multiple children.

• Panel is an abstract class deriving from FrameworkElement. There are several concrete classes representing different types of panels.

UIElement FrameworkElement Panel (abstract) Canvas DockPanel Grid StackPanel UniformGrid WrapPanel • Rather than specify precise size and location of

controls in a window, WPF prefers dynamic layout.

− The panels are responsible for sizing and positioning elements.

− The various classes deriving from Panel each support a particular kind of layout model.

Page 45: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 33 All Rights Reserved

Children of Panels

• Panel has a property Children that is used to store child elements.

− Children is an object of type UIElementCollection.

− UIElementCollection is a collection of UIElement objects.

• There is a great variety of elements that can be stored in a panel, including any kind of control.

• You can add a child element to a panel via the Add() method of UIElementCollection.

Dim panel As New StackPanel() ... Dim btnGreet As New Button() ... panel.Children.Add(btnGreet)

Page 46: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 34 All Rights Reserved

Example – TwoControls

• The example program TwoControls illustrates use of a StackPanel, whose children are a TextBox and a Button.

− See Step2.

− We provide a beige brush for the panel to help us see the extent of the panel in the window.

− The program also illustrates various automatic sizing features of WPF.

Page 47: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 35 All Rights Reserved

TwoControls – Code

• The TwoControls class derives from Window in the usual manner.

• A private member txtName is defined in the class, because we need to reference the TextBox in both the constructor and in the event handler.

Class TwoControls Inherits Window <STAThread()> _ Shared Sub Main(ByVal args() As String) Dim app As New Application() app.Run(New TwoControls()) End Sub Private txtName As TextBox Public Sub New() Title = "Two Controls Demo" Width = 288 Const MARGINSIZE As Integer = 10 ...

• A StackPanel is created and the Content of the main window is set to this new StackPanel.

Dim panel As New StackPanel() Content = panel

Page 48: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 36 All Rights Reserved

Automatic Sizing

• Only the width of the main window is specified.

• The height of the main window is sized to its content, which is a panel containing two controls.

Public Sub New() Title = "Two Controls Demo" Width = 288 Const MARGINSIZE As Integer = 10 Dim panel As New StackPanel() Content = panel SizeToContent = SizeToContent.Height panel.Background = Brushes.Beige panel.Margin = New Thickness(MARGINSIZE) ...

− Note that we are specifying a brush for the panel, and we are specifying a margin of 10 device-independent pixels.

• The TextBox specifies its width and horizontal alignment, and also a margin.

txtName = New TextBox() txtName.FontSize = 16 txtName.HorizontalAlignment = _ HorizontalAlignment.Center txtName.Width = Width / 2 txtName.Margin = New Thickness(MARGINSIZE) panel.Children.Add(txtName)

Page 49: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 37 All Rights Reserved

TwoControls – Code (Cont’d)

• The Button also specifies its horizontal alignment and a margin.

Dim btnGreet As New Button() btnGreet.Content = "Say Hello" btnGreet.FontSize = 16 btnGreet.HorizontalAlignment = _ HorizontalAlignment.Center btnGreet.Margin = New Thickness(MARGINSIZE) panel.Children.Add(btnGreet)

• Both the TextBox and the Button are added as children to the panel.

txtName = New TextBox() ... panel.Children.Add(txtName) Dim btnGreet As New Button() ... panel.Children.Add(btnGreet)

• The Click event of the Button is handled. AddHandler btnGreet.Click, _ AddressOf ButtonOnClick ... Private Sub ButtonOnClick(ByVal sender As _ Object, ByVal args As RoutedEventArgs) MessageBox.Show("Hello, " & txtName.Text, _ "Greeting") End Sub

Page 50: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 38 All Rights Reserved

Lab 1

A Windows Application with Two Controls

In this lab you will implement the TwoControls example program from scratch. This example will illustrate in detail the steps needed to create a new WPF application using Visual Studio 2008, and you will get practice with all the fundamental concepts of WPF that we’ve covered in this chapter.

Detailed instructions are contained in the Lab 1 write-up at the end of the chapter.

Suggested time: 30 minutes

Page 51: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 39 All Rights Reserved

Summary

• The goal of Windows Presentation Framework is to provide a unified framework for creating modern user experiences.

• WPF is a major component of the .NET Framework 3.0/3.5, layered on top of .NET Framework 2.0.

• The most fundamental WPF classes are Application and Window.

• You can create, build and run simple WPF programs using Visual Studio.

• You may specify a foreground or background of a window or control by means of a Brush.

• You can use panels to lay out Windows that have multiple controls.

Page 52: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 40 All Rights Reserved

Lab 1

A Windows Application with Two Controls

Introduction In this lab you will implement the TwoControls example program from scratch. This example will illustrate in detail the steps needed to create a new WPF application using Visual Studio 2008, and you will get practice with all the fundamental concepts of WPF that we’ve covered in this chapter. Suggested Time: 30 minutes Root Directory: OIC\WpfVb Directories: Labs\Lab1 (do your work here) Chap01\TwoControls\Step1 (answer to Part 1) Chap01\TwoControls\Step2 (answer to Part 2) Part 1. Create a WPF Application with a StackPanel In Part 1 you will use Visual Studio to create a WPF application. You will go on to create a StackPanel that has as children a TextBox and a Button. This first version does not provide an event handler for the button. Also, it does not handle sizing very well! 1. Use Visual Studio to create a new WPF application TwoControls in the Lab1 folder.

2. In Solution Explorer, delete the files App.xaml and Window1.xaml.

3. Add a new code file Program.vb to your project.

4. In Program.vb enter the following code, which does the minimum of creating Application and Window objects.

Namespace TwoControls Class TwoControls Inherits Window <STAThread()> _ Shared Sub Main(ByVal args() As String) Dim app As New Application() app.Run(New TwoControls()) End Sub Public Sub New() End Sub End Class End Namespace

Page 53: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 41 All Rights Reserved

5. Build and run. You should get a clean compile. You should see a main window, which has no title and an empty client area.

6. Add the following code to the TwoControls constructor.

Public Sub New() Title = "Two Controls Demo" Width = 288 End Sub 7. Build and run. Now you should see a title and the width as specified.

8. Now we are going to set the Content of the main window to a new StackPanel that we create. To be able to visually see the StackPanel, we will paint the background with a beige brush, and we’ll make the Margin of the StackPanel 10 device-independent pixels.

Public Sub New() Title = "Two Controls Demo" Width = 288 Const MARGINSIZE As Integer = 10 Dim panel As New StackPanel() Content = panel panel.Background = Brushes.Beige panel.Margin = New Thickness(MARGINSIZE) End Sub 9. Build and run your application. You should see the StackPanel displayed as solid

beige, with a small margin.

10. Next we will add a TextBox as a child of the panel. Since we will be referencing the TextBox in an event-handler method as well as the constructor, define a private data member txtName of type TextBox.

Private txtName As TextBox 11. Provide the following code to initialize txtName and add it as a child to the panel.

txtName = New TextBox() txtName.FontSize = 16 txtName.HorizontalAlignment = HorizontalAlignment.Center txtName.Width = Width / 2 panel.Children.Add(txtName) 12. Build and run. Now you should see the TextBox displayed, centered, at the top of the

panel.

13. Next, add code to initialize a Button and add it as a child to the panel.

Dim btnGreet As New Button()

Page 54: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 1

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 42 All Rights Reserved

btnGreet.Content = "Say Hello" btnGreet.FontSize = 16 btnGreet.HorizontalAlignment = HorizontalAlignment.Center panel.Children.Add(btnGreet) 14. Build and run. You should now see the two controls in the panel. You are now at

Step1.

Part 2. Event Handling and Layout In Part 2 you will handle the Click event of the button. You will also provide better layout of the two controls. 1. First, we’ll handle the Click event for the button. Provide this code to add a handler

for the Click event.

AddHandler btnGreet.Click, AddressOf ButtonOnClick 2. Provide this code for the handler, displaying a greeting to the person whose name is

entered in the text box.

Private Sub ButtonOnClick(ByVal sender As Object, _ ByVal args As RoutedEventArgs) MessageBox.Show("Hello, " & txtName.Text, "Greeting") End Sub 3. Build and run. The program now has its functionality, but the layout needs improving.

4. Provide the following code to size the height of the window to the size of its content.

SizeToContent = SizeToContent.Height 5. Build and run. Now the vertical sizing of the window is better, but the controls are

jammed up against each other.

6. To achieve a more attractive layout, provide the following statements to specify a margin around the text box and the button. You have a reasonable layout (Step2).

txtName.Margin = New Thickness(MARGINSIZE) ... btnGreet.Margin = New Thickness(MARGINSIZE)

Page 55: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 179 All Rights Reserved

Chapter 5

Dialogs

Page 56: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 180 All Rights Reserved

Dialogs

Objectives

After completing this unit you will be able to:

• Use various kinds of message boxes in your programs.

• Use WPF wrapper classes to access the Win32 common dialogs in your programs.

• Implement custom modal dialogs.

• Implement custom modeless dialogs.

Page 57: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 181 All Rights Reserved

Dialog Boxes in WPF

• A dialog box is a window in a Windows application used for interacting with the user.

• With a modal dialog box the user cannot work elsewhere in the application until the dialog is closed.

• With a modeless dialog box the user can work in another window in the application while the dialog remains on the screen.

• There are several types of dialog boxes you can use with WPF.

− A MessageBox is a simple modal dialog box that displays information and can receive yes/no input from the user.

− There are various predefined common dialog boxes that perform common input operations in a standardized manner.

− You can create custom dialog boxes.

Page 58: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 182 All Rights Reserved

MessageBox

• The simplest type of dialog is the message box.

− It is a modal dialog that can display informational messages. It can optionally specify a title, icon, and one or more buttons.

− If the message box has more than one button, it returns a MessageBoxResult value indicating which button the user pressed.

• The WPF MessageBox class is used to manage these message boxes.

− You cannot create a new instance of the MessageBox class (it has a private constructor).

− To display a message box, you must call the static method Show.

• The example program MessageBoxDemo illustrates a number of features of message boxes.

Page 59: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 183 All Rights Reserved

MessageBox Show Method

• The Show method has several parameters that define:

− The message text

− The title of the message box window

− The buttons that are displayed (a value from the MessageBoxButtons enumeration)

OK, OKCancel, YesNo, YesNoCancel

− The icon that is displayed (a value from the MessageBoxImage enumeration)

None, Question, Information, Asterisk, Exclamation, Error, Hand, Stop, Warning

Page 60: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 184 All Rights Reserved

MessageBox Examples

• Each of the following represents a valid call to the MessageBox's Show method:

' Show only the message and an OK button Dim msg As String = "Welcome " & txtName.Text & "!" MessageBox.Show(msg)

' Show the message, a title, and an OK button msg = "Welcome " & txtName.Text & "!" MessageBox.Show(msg, "Greeting")

Page 61: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 185 All Rights Reserved

MessageBox Examples (Cont’d)

' Show a message, title, error icon and an ' OK button MessageBox.Show("Name is required.", _ "Data Error", MessageBoxButton.OK, _ MessageBoxImage.Error)

' Ask the user a Yes/No question Dim answer As MessageBoxResult answer = MessageBox.Show( _ "Are you sure you want to close?", _ "MessageBox Demo", MessageBoxButton.YesNo, _ MessageBoxImage.Question) If answer <> MessageBoxResult.Yes Then ...

Page 62: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 186 All Rights Reserved

Closing a Form: Review

• There are several ways the user could close the main form in our example.

− From the “X” at the top right of the window.

− From the system menu at the top left of the window.

− By the keyboard Alt + F4.

− In our application by clicking the Close button

• When a form is about to be closed, the Closing event is fired.

• You can give the user a chance to stop closing by handling this event.

Private Sub Window_Closing( _ ByVal sender As Object, _ ByVal e As System.ComponentModel.CancelEventArgs) ' Ask the user a Yes/No question Dim answer As MessageBoxResult answer = MessageBox.Show( _ "Are you sure you want to close?", _ "MessageBox Demo", MessageBoxButton.YesNo, _ MessageBoxImage.Question) If answer <> MessageBoxResult.Yes Then e.Cancel = True End If End Sub

Page 63: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 187 All Rights Reserved

Common Dialog Boxes

• Windows provides a number of dialog boxes that are common to all applications.

− This provides a consistent user interface for users, as well as simplifies the development task for programmers.

• WPF encapsulates several of these common dialogs in managed classes in the Microsoft.Win32 namespace:

− OpenFileDialog

− SaveFileDialog

− PrintDialog

• We illustrate use of the OpenFileDialog class.

− See example program FileOpen in the chapter directory.

Page 64: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 188 All Rights Reserved

FileOpen Example

• Clicking the button brings up the Open File common dialog box.

− You can navigate to parent directory by the button.

• We have designated .xaml files as the default file extension in which this application is interested.

• Clicking the Open button will now open the designated file, which the application will show in the text box.

Page 65: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 189 All Rights Reserved

FileOpen Example Code

Private Sub btnBrowse_Click(ByVal sender As _ Object, ByVal args As RoutedEventArgs) Dim dlg As New OpenFileDialog() dlg.DefaultExt = ".xaml" ' Default file extension dlg.Filter = "XAML Files (.xaml)|*.xaml" If dlg.ShowDialog() = True Then txtFile.Text = dlg.FileName Open() End If End Sub Private Sub btnOpen_Click(ByVal sender As Object, _ ByVal args As RoutedEventArgs) Open() End Sub Private Sub Open() txtData.Text = "" Dim NL As String = Environment.NewLine Dim reader As StreamReader = _ File.OpenText(txtFile.Text) Dim str As String str = reader.ReadLine() Do While str IsNot Nothing txtData.Text += str & NL str = reader.ReadLine() Loop End Sub

Page 66: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 190 All Rights Reserved

Custom Dialogs

• There are two types of custom dialogs:

− Modal dialogs appear as popup windows. They maintain focus within the application until they are closed. You cannot cause other windows within the application to gain focus by clicking on them while the modal dialog is displayed.

− Modeless dialogs appear as popup windows. However, other windows within the application can gain focus by clicking on them while the modeless dialog is displayed.

• You can typically tell modal and modeless dialogs apart from their design.

− Modal dialogs have OK and Cancel buttons

− Modeless dialogs typically have Apply and Close buttons.

Page 67: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 191 All Rights Reserved

Modal Dialogs

• To create and use a custom modal dialog, do the following:

− Add another window to a project, both XAML and code-behind files, and configure properties on the new dialog to control its appearance.

− Set the DialogResult properties of the OK and Cancel buttons so that you can return a dialog result when they are clicked.

− Provide code in the dialog class to expose as properties the information you want to pass between the main window and the dialog.

− Write code to display the dialog.

− Write code to respond to the dialog result.

Page 68: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 192 All Rights Reserved

Modal Dialog Example

• To demonstrate the use of custom modal dialogs, we will design an application that allows the user to add and delete products from a simple list.

− This example does not attempt to persist any data.

• Our example program is called DialogDemo.

− It consists of a main form designed as you see below.

− Note the three dots on the Add a Product button, indicating that clicking it will bring up a dialog box.

Page 69: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 193 All Rights Reserved

New Product Dialog

• The New Product Dialog provides a simple form for entering a description, a price, and a unit.

• There are a number of features in this typical user interface for a modal dialog box:

− The window is not resizeable.

− A dialog result of OK can be returned by either clicking the OK button or pressing the Enter key.

− A dialog result of cancel can be returned by clicking the Cancel button, clicking the X in the top-right, or pressing the Escape key.

− The dialog does not show up in the Windows Taskbar.

Page 70: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 194 All Rights Reserved

XAML for New Product Dialog

<Window x:Class="NewProductDlg" ... Title="New Product" Width="250" SizeToContent="Height" ResizeMode="NoResize" ShowInTaskbar="False" Loaded="Window_Loaded"> <Grid> ... <Label Grid.Row="0" Grid.Column="0" Margin="5"> Description </Label> <TextBox Name="txtDesc" Grid.Row="0" Grid.Column="1" Margin="5"> </TextBox> ... <Button Name="btnOK" IsDefault="True" Click="btnOK_Click" Grid.Row="3" Grid.Column="0" Margin="5"> OK </Button> <Button Name="btnCancel" IsCancel="True" Grid.Row="3" Grid.Column="1" Margin="5"> Cancel </Button> </Grid> </Window>

Page 71: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 195 All Rights Reserved

Code for New Product Dialog

Private Sub Window_Loaded( _ ByVal sender As System.Object, _ ByVal e As System.Windows.RoutedEventArgs) cmbUnit.Items.Add("can") cmbUnit.Items.Add("dozen") cmbUnit.Items.Add("gallon") cmbUnit.Items.Add("loaf") cmbUnit.Items.Add("pound") cmbUnit.Text = cmbUnit.Items(0).ToString() End Sub Private Sub btnOK_Click(ByVal sender As Object, _ ByVal args As RoutedEventArgs) ' ShowDialog() will return true Me.DialogResult = True End Sub Public Property Description() As String Get Return txtDesc.Text End Get Set(ByVal value As String) txtDesc.Text = value End Set End Property Public Property Price() As Double Get Return Convert.ToDouble(txtPrice.Text) End Get Set(ByVal value As Double) txtPrice.Text = value.ToString() End Set End Property ' Other properties ...

Page 72: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 196 All Rights Reserved

Bringing up the Dialog

• To display the dialog, we must remember that any window in WPF is an instance of a class derived from System.Windows.Window.

− Therefore, to create a new dialog, we must create an instance of the class.

− To show the dialog modally, we must call the window’s ShowDialog() method.

• In the Click event handler for "Add a Product" on the main window, we can write the following code:

Private Sub btnAdd_Click(ByVal sender As Object, _ ByVal args As RoutedEventArgs) Dim dlg As New NewProductDlg() dlg.Description = "Tuna" dlg.Price = 1.59 dlg.Owner = Me Dim ok As Boolean = CBool(dlg.ShowDialog()) If ok Then Dim desc As String = dlg.Description Dim price As Double = dlg.Price Dim unit As String = dlg.Unit AddProduct(desc, price, unit) End If End Sub

− ShowDialog() returns a Nullable(Of Boolean), so it must be cast to a Boolean.

− Note the use of properties for setting and retrieving data in the dialog box.

Page 73: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 197 All Rights Reserved

Dialog Box Owner

• You should specify an owner of the dialog box to support UI automation.

dlg.Owner = Me Dim ok As Boolean = CBool(dlg.ShowDialog())

• UI Automation is the new accessibility framework for Windows, available on all operating systems that support WPF.

− UI Automation provides programmatic access to most user interface elements on the desktop.

− This enables assistive technology products such as screen readers to provide information about the UI to end users and to manipulate the UI by means other than standard input.

− UI Automation also allows automated test scripts to interact with the UI.

• Specifying the main window as the owner of the dialog will also ensure that the dialog is shown whenever the main window is shown.

− Try commenting out the line assigning an owner and see what happens if you bring up the dialog, then switch to another application, and then come back to the DialogDemo application.

Page 74: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 198 All Rights Reserved

Modeless Dialog Box Example

• Although fully functional, the modal dialog box UI is not too convenient.

− You can only add one item at a time.

− You can’t delete any items when the new product dialog box is open.

• A more convenient user interface is offered by the ModelessDemo example program.

− You can bounce back and forth at will between the two windows.

Page 75: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 199 All Rights Reserved

Displaying the Dialog

• To display the dialog we use, we use a different method in the Window class.

− In place of ShowDialog(), we call the method Show() to display the dialog modelessly.

• In the Click event handler for “Add a Product” in the main window, we provide the following code:

... Dim dlg As New NewProductDlg() dlgNewProduct = dlg dlg.mainWindow = Me dlg.Owner = Me dlg.Show() ...

− dlgNewProduct is a public data member of the main window class that provides a reference to the dialog.

Class Window1 Public dlgNewProduct As NewProductDlg = Nothing ...

− mainWindow is a public data member of the dialog class that provides a reference to the main window.

Partial Public Class NewProductDlg Public mainWindow As Window1 ...

• The dialog class uses mainWindow for communicating with the parent.

Page 76: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 200 All Rights Reserved

XAML for Modeless Dialog

• In the XAML we make two changes.

− Change the text (and corresponding names) of the buttons to Apply and Close.

− Provide a Click handler for each button.

<Button Name="btnApply" IsDefault="True" Click="btnApply_Click" Grid.Row="3" Grid.Column="0" Margin="5"> Apply </Button> <Button Name="btnClose" IsCancel="True" Click="btnClose_Click" Grid.Row="3" Grid.Column="1" Margin="5"> Close </Button>

Page 77: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 201 All Rights Reserved

Handler for the Apply Button

• In the case of a modeless dialog, the handler of the Apply button must kick off the update of the main window.

− In our example, we will perform the update ourselves, making use of the mainWindow reference.

Private Sub btnApply_Click(ByVal sender As _ Object, ByVal args As RoutedEventArgs) mainWindow.AddProduct(Description, Price, Unit) txtDesc.Text = "" txtPrice.Text = "" txtDesc.Focus() End Sub

− For the convenience of the user, we also clear out the text boxes for description and price, and we set the focus to the text box for description.

• For this approach to work, the AddProduct() method in the main window must now be public.

Public Sub AddProduct(ByVal desc As String, _ ByVal price As Double, ByVal unit As String) Dim aLine As String = _ String.Format("{0} - {1:C}/{2}", _ desc, price, unit) lstProducts.Items.Add(aLine) End Sub

Page 78: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 202 All Rights Reserved

Handler for the Close Button

• In a modal dialog, we don’t need a handler for the Cancel button.

− Setting the IsCancel property to true will automatically provide the desired behavior.

• In the case of a modeless dialog, we must provide a handler for the Click event of the Close button.

− This handler simply closes the window.

Private Sub btnClose_Click(ByVal sender As _ Object, ByVal args As RoutedEventArgs) Close() End Sub

Page 79: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 203 All Rights Reserved

Instances of a Modeless Dialog

• Since the dialog is modeless, there is nothing to prevent the user from clicking the Add a Product button while an instance of the dialog is open.

− This could result in a second instance of the dialog being displayed.

• To ensure only a single instance, we make use of the reference to the dialog mentioned earlier.

− It is initialized to Nothing and set back to Nothing by the dialog when it is closed in a handler for the Closed event.

' In main window Class Window1 Public dlgNewProduct As NewProductDlg = Nothing ... ' In modeless dialog ... Private Sub Window_Closed(ByVal sender As Object, _ ByVal e As EventArgs) mainWindow.dlgNewProduct = Nothing End Sub

Page 80: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 204 All Rights Reserved

Checking for an Instance

• When bringing up the modeless dialog we first check to see if dlgNewProduct is Nothing.

− If not, there is an instance open already, and we simply set the focus to it.

Private Sub btnAdd_Click(ByVal sender As _ Object, ByVal args As RoutedEventArgs) If dlgNewProduct Is Nothing Then Dim dlg As New NewProductDlg() dlgNewProduct = dlg dlg.mainWindow = Me dlg.Owner = Me dlg.Show() Else dlgNewProduct.Focus() End If End Sub

Page 81: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 205 All Rights Reserved

Lab 5

Dialogs for the Simple Editor

In this lab you will enhance your simple editor by providing common dialogs for opening and saving a file. You will also implement a custom dialog for changing the font that is used.

Detailed instructions are contained in the Lab 5 write-up at the end of the chapter.

Suggested time: 60 minutes

Page 82: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 206 All Rights Reserved

Summary

• MessageBox is the simplest type of dialog in .NET.

− It can display informational messages, and can optionally specify a title, an image, and one or more buttons.

− If the message box has more than one button, it returns a MessageBoxResult value indicating which button the user pressed.

• WPF provides wrapper classes for some of the Windows Common Dialogs.

− These dialogs are part of the Windows operating systems and are available for all applications to use.

• There are two types of custom dialogs:

− Modal dialogs appear as popup windows. They maintain focus within the application until they are closed. You cannot cause other windows within the application to gain focus by clicking on them while the modal dialog is displayed.

− Modeless dialogs appear as popup windows. However, other windows within the application can gain focus by clicking on them while the modeless dialog is displayed.

• Modal forms are displayed using ShowDialog(); modeless dialogs are displayed using Show().

Page 83: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 207 All Rights Reserved

Lab 5

Dialogs for the Simple Editor

Introduction In this lab you will enhance your simple editor by providing common dialogs for opening and saving a file. You will also implement a custom dialog for changing the font that is used. Suggested Time: 60 minutes Root Directory: OIC\WpfVb Directories: Labs\Lab5\Editor (do your work here)

Chap04\Editor\Step2 (backup of starter code) Chap05\Editor\Step3 (answer)

Part 1. Open File Dialog In this part you will provide an Open File Dialog so that you can open any file rather than just the hardcoded file data.txt. 1. If you would like to continue with your own version of the Editor, delete the supplied

starter files and replace them with your files from the Lab4A folder. Build and run your starter code.

2. Provide a method Open(ByVal path As String) that will open the file with the specified path. Move your code from the handler for the Open button to this method, replacing the hardcoded data.txt with path.

3. In btnOpen_Click() call Open(“data.txt”).

4. Build and run. You’ll hit an exception because the file data.txt is not found in bin\Debug, the default current directory.

5. Place your code in the Open() method in a Try block. In the Catch handler display the error message associated with the exception using a message box. You should display the error message, the title “Error”, an OK button, and the error icon.

6. Build and run. Now you should see your own exception handling.

7. Copy the file data.txt to bin\Debug. Run again. Now the file should be opened and the contents displayed in the text box.

Page 84: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 208 All Rights Reserved

8. In preparation for using the common dialogs, bring in the Microsoft.Win32 namespace.

9. In btnOpen_Click() provide barebones code to open and display a file using the OpenFileDialog class.

Dim dlg As New OpenFileDialog() If dlg.ShowDialog() = True Then Open(dlg.FileName) End If 10. Build and run. You should now be able to navigate to any file using the dialog and

then open the file. But the dialog you are shown is indeed rather barebones, as the “File of type” dropdown is empty.

11. Provide a filter for either Text (*.txt) or XAML (*.xaml) files.

dlg.Filter = "Text Files (.txt)|*.txt|XAML Files (.xaml)|*.xaml" 12. Build and run. Now you will see a more interesting dialog.

13. Try to open Window1.xaml.vb. You can’t navigate to it! (But you can still open the file if you remember its name by typing it in the File name combobox.) Provide an additional file type All Files (*.*) in your filter.

dlg.Filter = "Text Files (.txt)|*.txt|XAML Files (.xaml)|*.xaml" _ & "|All Files (*.*)|*.*" 14. Build and run. Now you should be able to conveniently navigate to any file, with .txt

and .xaml files given special notice.

15. As a final experiment, in the Open dialog try entering some non-existent file, such as junk.txt. You will see an error message. You can tell from the title of the message box that it is provided by the common dialog, not your own exception handling.

Page 85: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 209 All Rights Reserved

Part 2. Save File Dialog In Part 2 you will provide a Save File Dialog so that you can save to any file, not just the hardcoded data.txt. 1. Provide a method Save(ByVal path As String) that will save the file to the specified

path. Move your code from the handler for the Save button to this method, replacing the hardcoded data.txt with path.

2. In btnSave_Click() call Save(“data.txt”).

3. Build and run. The program should work as before.

4. In btnSave_Click() provide code to save using the SaveFileDialog class. Use the same filter that you used with OpenFileDialog.

Dim dlg As New SaveFileDialog() dlg.Filter = "Text Files (.txt)|*.txt|XAML Files (.xaml)|*.xaml" & _ "|All Files (*.*)|*.*" If dlg.ShowDialog() = True Then Save(dlg.FileName) End If 5. Build and run. You should now be able to save a file to any path.

6. You can enhance the behavior by providing both a default extension and a default document name.

7. Build and run. Try saving to various files and open to see the result. You may run across a small problem in Open—the previous text is shown along with the new text. Fix this.

Private Sub Open(ByVal path As String) Try txtData.Clear() ... 8. Build and run. As a further experiment, try saving to an invalid file name, such as ///.

The common dialog will handle this error for you.

Page 86: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 210 All Rights Reserved

Part 3. A Custom Dialog for Changing Font

In Part 3 you will provide a dialog to allow the user to change the font used for displaying the text. Windows provides a common font dialog, but this dialog is not yet encapsulated for WPF in Microsoft.Win32. So we’ll create a simple custom dialog to do the job. Our version will only allow the user to change the FontSize and the FontFamily. If you have extra time, you may wish to enhance the dialog to allow user control over additional font features, which you can find documented in MSDN in the Typeface class in the System.Windows.Media namespace.

1. In Window1.xaml, add a fourth button to bring up a font dialog. The content should be “Font ...”, the three dots indicating that clicking the button will bring up a dialog. Make sure that the Margin properties on your buttons are such that you have an even 10 unit margin all around. Also, add the three dots to the Open and Save buttons, as they also now bring up dialogs.

2. In Window1.xaml.vb provide a skeleton handler for the Click event of the new Font button.

3. Build and run. The user interface should now show the four buttons, the three dots on each button that brings up a dialog, and margins should be uniform.

4. Next, we’ll create the font dialog. We will need both a XAML file and a code-behind file. To get started, copy the files NewProductDlg.xaml and NewProductDlg.xaml.vb from the DialogDemo example and rename them to FontDlg.xaml and FontDlg.xaml.vb.

5. Edit the XAML in FontDlg.xaml to create this user interface:

Page 87: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 211 All Rights Reserved

6. Edit FontDlg.Xaml.vb to make the class name FontDlg and to provide properties Size (of type Double) and Family (of type String). Note that you should not call these properties FontSize and FontFamily, because that would hide properties of the same name inherited from the Window class.

7. Provide code in the handler for the Font button to bring up the dialog. Try to initialize the Size and Family properties.

Private Sub btnFont_Click(ByVal sender As Object, _ ByVal args As RoutedEventArgs) Dim dlg As New FontDlg() dlg.Size = Me.FontSize dlg.Family = Me.FontFamily.Source dlg.Owner = Me Dim ok As Boolean = CBool(dlg.ShowDialog()) If ok Then Me.FontSize = dlg.Size Me.FontFamily = New FontFamily(dlg.Family) End If End Sub 8. Build and run. You may see that the FontSize has been initialized but not the

FontFamily. Try changing the FontSize. This should work. Can you type a new name, such as Arial, into the FontFamily combo box?

9. By default, a combo box is not editable. You can make it so by making setting the IsEditable property to True.

<ComboBox Name="cmbFontFamily" Grid.Row="1" Grid.Column="1" IsEditable="True" Margin="5"> </ComboBox> 10. Build and run. The selection box is now initialized, but the list of available fonts has

not been populated.

11. In FontDlg.xaml add a handler for the Loaded event of Window.

Page 88: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 5

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 212 All Rights Reserved

12. Navigate to the new event handler and provide the following code. It iterates through all the font families in the Fonts.SystemFontFamilies collection.

Private Sub Window_Loaded(ByVal sender As System.Object, _ ByVal e As System.Windows.RoutedEventArgs) For Each fam As FontFamily In Fonts.SystemFontFamilies cmbFontFamily.Items.Add(fam.Source) Next fam End Sub 13. Build and run. You should now be able to change font sizes and font families. There

is just one problem. When you change the font, you not only change the font in the text box, but you also change the fonts in the buttons!

14. Go back to the code where we bring up the font dialog. We have been using Me for getting and setting the font properties. We really should use txtData, specifying properties for just the text box, not the whole window.

Private Sub btnFont_Click(ByVal sender As Object, _ ByVal args As RoutedEventArgs) Dim dlg As New FontDlg() dlg.Size = txtData.FontSize dlg.Family = txtData.FontFamily.Source dlg.Owner = Me Dim ok As Boolean = CBool(dlg.ShowDialog()) If ok Then txtData.FontSize = dlg.Size txtData.FontFamily = New FontFamily(dlg.Family) End If End Sub 15. Build and run. Our little editor should now have the functionality to change font used

in the text box. For example, we’ve changed the font to Times New Roman 16.

Page 89: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 9

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 301 All Rights Reserved

Chapter 9

Resources

Page 90: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 9

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 302 All Rights Reserved

Resources

Objectives

After completing this unit you will be able to:

• Understand what resources are and how you can use them throughout the application.

• Take advantage of using logical resources, a new type of resource supported by WPF.

• Use resources from XAML and from procedural code.

• Understand the difference between the StaticResource and DynamicResource markup extensions.

Page 91: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 9

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 303 All Rights Reserved

Resources in .NET

• Resources are parts of a program that aren’t code.

• You can think of resources as images, fonts, audio files and video files.

• Resources can even be just a collection of strings.

− This is largely used to add multi-language support to an application.

− Instead of writing a literal directly into the code, you just make a reference to a string in a resource file.

− Then you can use .NET framework classes to load different resource files for each culture / language.

Page 92: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 9

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 304 All Rights Reserved

Resources in WPF

• The core .NET resources system is supported by WPF.

• Additionally, WPF supports a number of new features.

• There are two types of resources in WPF: binary resources and logical resources.

− Binary resources are common items like images or audio files.

− Logical resources can be any arbitrary .NET object.

Page 93: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 9

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 305 All Rights Reserved

Binary Resources

• Binary resources are everything that was known as resources in .NET framework so far.

• WPF stores compiled XAML files as binary resources behind the scenes.

• This type of resources can be put into two categories:

− Localizable resources which can be different depending on culture.

− Language-neutral resources that do not depend on culture.

• A typical way of defining a resource is to add the file to the Visual Studio project and set a build action for it.

− By doing this, the resource will be packaged into the project

assembly.

− This is important if the resource must be localized later.

Page 94: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 9

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 306 All Rights Reserved

Loose Files as Resources

• An alternative to this is to use the Content build action.

− But if you do so, you should change the Copy to output

directory property to Copy always of Copy if newer, because the resource won’t be embedded in the assembly.

− As the resource will be a loose file in the output directory, you can easily update the file without needing to rebuild or deploy the application again.

• You can still use a resource that has not been added to the project (despite this being not satisfactory).

− You can reference the resource using the full path.

<Button Margin="10"> <Image Source="c:\OIC\Data\Graphics\MISC20.ICO"/> </Button>

• It’s still possible to reference a resource programmatically.

− This is useful then the resource is generated at run-time.

Page 95: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 9

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 307 All Rights Reserved

Binary Resources Example

• Examine the code in the CalculatorResources folder in the chapter directory.

− There is a StackPanel with four buttons.

− The buttons have an image as their content, referenced as a relative path inside the project.

<Button Margin="10" Name="btnAdd" Click="btnAdd_Click"> <Image Source="Graphics/MISC18.ICO"/> </Button>

− The images were added to the project, with the build action set to Resource and they are not copied to the output directory.

Page 96: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 9

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 308 All Rights Reserved

Logical Resources

• Logical resources are a new type of resource specific to WPF.

• Any .NET object can be a logical resource.

• The object must be stored and named in a resources property (that is a collection) to be used along the code.

− The resources property can be set locally in a XAML element or in a higher scope.

− The code below defines a Resources property in the Window element, with three different SolidColorBrush objects.

<Window x:Class="SimpleBrushXaml.SimpleBrush" ...> <Window.Resources> <SolidColorBrush x:Key="windowBackgroundBrush">Beige </SolidColorBrush> <SolidColorBrush x:Key="buttonBackgroundBrush">LightGreen </SolidColorBrush> <SolidColorBrush x:Key="buttonForegroundBrush">Blue </SolidColorBrush> </Window.Resources> ...

Page 97: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 9

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 309 All Rights Reserved

Logical Resources (Cont’d)

• The resources defined in the Window element are visible to any element that is below the Window in the element’s tree hierarchy.

− The x:Key property defines a name under which the resource will be visible to other elements.

− The resource is referenced using the StaticResource markup extension, which is responsible for finding the resource.

<Button Name="btnSayHello" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center" Background="{StaticResource buttonBackgroundBrush}" Foreground="{StaticResource buttonForegroundBrush}" Click="BtnSayHello_Click">

• We’ll see more on the StaticResource markup extension later in this chapter.

Page 98: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 9

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 310 All Rights Reserved

Logical Resources Demo

• We’ll illustrate the use of logical resources with the solution in the Demos\SimpleBrush folder, backed up in SimpleBrush\Step1 in the chapter directory.

1. Build and run the SimpleBrushXaml solution. You’ll see a simple window with just one button as the content.

2. In the XAML code, the button and the window have some color formatting defined directly in the element’s syntax.

<Window ... Title="Simple Brushes" Height="192" Width="288" Background="Beige"> <Button Name="btnSayHello" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center" Background="LightGreen" Foreground="Blue" Click="BtnSayHello_Click"> Say Hello </Button> </Window>

Page 99: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 9

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 311 All Rights Reserved

Logical Resources Demo (Cont’d)

3. We have seen before that the colors used as background and foreground are brushes. Add these Brush objects to the Window’s resource collection.

<Window ... Background="Beige"> <Window.Resources> <SolidColorBrush x:Key="windowBackgroundBrush">Beige </SolidColorBrush> <SolidColorBrush x:Key="buttonBackgroundBrush">LightGreen </SolidColorBrush> <SolidColorBrush x:Key="buttonForegroundBrush">Blue </SolidColorBrush> </Window.Resources> ... 4. Now you can replace the current Background and Foreground

values by a reference to the appropriate resource.

<Button Name="btnSayHello" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center" Background="{StaticResource buttonBackgroundBrush}" Foreground="{StaticResource buttonForegroundBrush}" Click="BtnSayHello_Click"> Say Hello </Button>

Page 100: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 9

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 312 All Rights Reserved

Logical Resources Demo (Cont’d)

5. Build and run the application. You’ll see that everything sill works as before, but now the button uses resources for the background and foreground colors.

6. Now you can replace the Background property value of the Window element.

<Window ... Title="Simple Brushes" Height="192" Width="288" Background="{StaticResource windowBackgroundBrush}"> 7. Build the application and run it in the debug mode (press F5).

You’ll hit an exception because windowBackgroundBrush isn’t defined yet. (Notice that the resources are defined after this code section.)

8. As a workaround, we can change the way we set the Window’s Background property. Remove the property from the Window tag and set this property after the resources are defined.

<Window ... Title="Simple Brushes" Height="192" Width="288"> <Window.Resources> <SolidColorBrush x:Key="windowBackgroundBrush">Beige </SolidColorBrush> ... </Window.Resources> <Window.Background> <StaticResource ResourceKey="windowBackgroundBrush"/> </Window.Background>

Page 101: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 9

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 313 All Rights Reserved

Logical Resources in Code

9. Build and run the application. Now the application is using resources defined in XAML for brushes.

− The application is saved at this point in the SimpleBrush\Step2 folder in the chapter directory.

− Going further, we can change this application to still use resources, but in procedural code.

10. Continuing with the demo, open the code-behind file SimpleBrush.xaml.vb.

11. Add the three brushes as resources just before the InitializeComponent() call.

Public Sub New() Me.Resources.Add("windowBackgroundBrush", _ New SolidColorBrush(Colors.Beige)) Me.Resources.Add("buttonBackgroundBrush", _ New SolidColorBrush(Colors.LightGreen)) Me.Resources.Add("buttonForegroundBrush", _ New SolidColorBrush(Colors.Blue)) InitializeComponent() End Sub 12. Now you can remove the Window.Resources tag from the

XAML, as the resources are already defined in the code-behind file.

13. Build and run the application, and note that everything still works as before. The resources are being defined programmatically, but accessed through XAML.

Page 102: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 9

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 314 All Rights Reserved

Logical Resources in Code (Cont’d)

14. Now we’ll change the code to set the properties accessing the resources programmatically. Do this just after the InitializeComponent() call.

Public Sub New() Me.Resources.Add("windowBackgroundBrush", _ New SolidColorBrush(Colors.Beige)) Me.Resources.Add("buttonBackgroundBrush", _ New SolidColorBrush(Colors.LightGreen)) Me.Resources.Add("buttonForegroundBrush", _ New SolidColorBrush(Colors.Blue)) InitializeComponent() Me.Background = CType( _ Me.Resources("windowBackgroundBrush"), Brush) btnSayHello.Background = CType( _ Me.Resources("buttonBackgroundBrush"), Brush) btnSayHello.Foreground = CType( _ Me.Resources("buttonForegroundBrush"), Brush) End Sub 15. Remove the Background and Foreground properties from

the Button tag, and the Window.Background tag.

16. Build and run the application. Everything works fine as before, using resources defined and accessed programmatically!

• The application is saved at this point in the SimpleBrush\Step3 folder in the chapter directory.

Page 103: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 9

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 315 All Rights Reserved

Static Resources

• As seen before, the StaticResource markup extension looks for a resource using a key, passed as a parameter.

<Button Name="btnSayHello" ... Background="{StaticResource buttonBackgroundBrush}" Foreground="{StaticResource buttonForegroundBrush}" ... </Button>

• This key corresponds to an x:Key parameter of a resource defined somewhere in the application.

• The resource can be defined within many scopes in the application. It can be defined:

− Inside any element’s resource property.

− In the resource property of any parent element.

− In the resource property of the Application object.

• The StaticResource markup extension will look for the resource following the order above, and if not found, it throws an InvalidOperationException.

− Hence, we can improve the sharing capability of a resource if we define it in the root element.

Page 104: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 9

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 316 All Rights Reserved

Dynamic Resources

• The StaticResource markup extension, seen in the previous page, applies the resource only once (actually, in the first time it’s needed).

• If we use the DynamicResource markup extension instead, we’re telling WPF that we want the resource to be applied every time it changes.

− Hence, it’s important to consider an overhead on looking for resource updates.

• StaticResource can be used almost anywhere in the code, and DynamicResource can only be used to set dependency property values.

− Dependency properties were discussed in the preceding chapter.

Page 105: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 9

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 317 All Rights Reserved

DynamicResource Example

• See SimpleBrushDynamic in the chapter directory for a DynamicResource usage example.

− The first think to notice is that we can set a property using DynamicResource even if the resource will be defined later in the code. We’ve already seen that this is not possible when using StaticResource.

<Window ... Background="{DynamicResource windowBackgroundBrush}"> <Window.Resources> <SolidColorBrush x:Key="windowBackgroundBrush">Beige </SolidColorBrush> ... </Window.Resources>

• The example contains two buttons, and its Background and Foreground properties are set to the same resources, but one uses StaticResource and the other uses DynamicResource.

• Additionally, there is a ComboBox that changes the resource buttonBackgroundBrush.

• Build and run the application.

− Notice that when you change the color of the SolidColorBrush resource using the ComboBox, only the button that uses DynamicResource has its Background updated.

Page 106: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 9

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 318 All Rights Reserved

Lab 9

Adding Some Colors to the Calculator

In this lab you will use your knowledge on resources to improve a colorful version of the Calculator program. You are provided with a starter solution that uses some brushes directly referenced in each element’s properties, and there are buttons that use full path for its images. You will define resources for the brushes and configure the images as binary resources in the project.

Detailed instructions are contained in the Lab 9 write-up at the end of the chapter.

Suggested time: 30 minutes

Page 107: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 9

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 319 All Rights Reserved

Summary

• Resources are parts of a program that aren’t code.

• Logical resources are a new type of resources supported by WPF, and it can store any .NET object.

• Resources can be used from XAML and from procedural code.

• You can use the StaticResource and DynamicResource markup extensions to reference a resource.

Page 108: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 9

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 320 All Rights Reserved

Lab 9

Adding Some Colors to the Calculator

Introduction In this lab you will use your knowledge on resources to improve a colorful version of the Calculator program. You are provided with a starter solution that uses some brushes directly referenced in each element’s properties, and there are buttons that use full path for its images. You will define resources for the brushes and configure the images as binary resources in the project.

Suggested Time: 30 minutes

Root Directory: OIC\WpfVb Directories: Labs\Lab9\CalculatorColors (do your work here)

Chap09\CalculatorColors\Step1 (backup of starter code) Chap09\CalculatorColors\Step2 (answer to Part 1) Chap09\CalculatorColors\Step3 (answer to Part 2)

Part 1. Using Binary Resources 1. Build and run the starter program. Notice that this is exactly the Calculator program

that you know, but the design was changed a bit to use some color brushes.

2. Examine the file Calculator.xaml. You will find four buttons, with images that are references using full path.

<Button Margin="10" Name="btnAdd" Click="btnAdd_Click"> <Image Source="C:\OIC\Data\Graphics\MISC18.ICO"/> </Button>

Page 109: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 9

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 321 All Rights Reserved

3. This is not a good practice. Copy the image files from the OIC\Data folder to a new

Graphics directory inside the project folder and add them to the project.

4. Now, change the references to the images by the new relative path inside the project. Do this for the four images.

<Button Margin="10" Name="btnAdd" Click="btnAdd_Click"> <Image Source="Graphics/MISC18.ICO"/> </Button> 5. Build and run your application. You’ll see that the images are shown correctly as

before, but now they are references as binary resources inside the project.

6. Close the application window and show the properties of the MISC18.ICO file.

Page 110: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 9

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 322 All Rights Reserved

7. By default, the image files have the Build Action property set to Resource and the Copy to Output Directory property set to Do not copy, so this way the files are embedded to the compiled assembly. You can check this by going to the bin\Debug folder in the project directory and see that the image files are not there, despite being correctly shown in the application window. Let’s assume that we want the images to be easily replaced if necessary, without needing to rebuild the project. To achieve this, change each image’s properties so that the Build Action is set to Content and the Copy to Output Directory is set to Copy if newer.

8. Build and run the application. The images are still being shown as expected, but now you can see them in the Graphics folder that was copied to the bin\Debug folder in the project directory. This gives you the flexibility we want, if we need to change the images easily. You are now at step 2.

Part 2. Using Logical Resources 1. Examine the file Calculator.xaml. Note that the colors used in the interface are

brushes that are directly set in the elements’ properties.

<StackPanel Background="LightBlue"> <StackPanel Orientation="Horizontal"> <Label Margin="10" Target="{Binding ElementName=txtOp1}" Foreground="Olive" > Operand _1: </Label> <TextBox Margin="10" Width="72" Name="txtOp1" BorderBrush="DarkGray" > <TextBox.Background> <LinearGradientBrush StartPoint="1,0" EndPoint="1,1"> <GradientStop Color="White" Offset="0"/> <GradientStop Color="LightGray" Offset="1"/> </LinearGradientBrush> </TextBox.Background> </TextBox> ... 2. These brushes could be set using resources. Let’s start defining a resource for the root

StackPanel’s Background color. Add a Window.Resources element just before this StackPanel, and define a new SolidColorBrush for the LightBlue color and assign the key windowBackground to it.

... <Window.Resources> <SolidColorBrush x:Key="windowBackground" Color="LightBlue"/> </Window.Resources> <StackPanel Background="LightBlue"> ...

Page 111: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 9

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 323 All Rights Reserved

3. Now, change the background property to reference the new resource using the

StaticResource markup extension.

<StackPanel Background="{StaticResource windowBackground}"> ... 4. Build and run the application. Notice that the light blue background is there, but now

referenced as a reusable resource.

5. Now let’s do the same with all the labels’ Foreground property and all the textboxes’ BorderBrush property. The key for the labels’ Foreground color should be textForeground and for the textboxes’ BorderBrush color should be boxBorders. Don’t forget to replace the references for these properties for all the three labels and textboxes!

<Window.Resources> <SolidColorBrush x:Key="windowBackground" Color="LightBlue"/> <SolidColorBrush x:Key="textForeground" Color="Olive"/> <SolidColorBrush x:Key="boxBorders" Color="DarkGray"/> </Window.Resources> <StackPanel Background="{StaticResource windowBackground}"> <StackPanel Orientation="Horizontal"> <Label Margin="10" Target="{Binding ElementName=txtOp1}" Foreground="{StaticResource textForeground}" > Operand _1: </Label> <TextBox Margin="10" Width="72" Name="txtOp1" BorderBrush="{StaticResource boxBorders}" > ... 6. Build the application to check that it’s compiling.

7. Now let’s add the last resource. It’s the gradient used as background in the textboxes. You can just copy the LinearGradientBrush from one of the textboxes to the Window.Resources element and add an x:Key property to it. Set the key to boxGradient.

<Window.Resources> <SolidColorBrush x:Key="windowBackground" Color="LightBlue"/> <SolidColorBrush x:Key="textForeground" Color="Olive"/> <SolidColorBrush x:Key="boxBorders" Color="DarkGray"/> <LinearGradientBrush x:Key="boxGradient" StartPoint="1,0" EndPoint="1,1"> <GradientStop Color="White" Offset="0"/> <GradientStop Color="LightGray" Offset="1"/> </LinearGradientBrush>

Page 112: Windows Presentation Foundation Using Visual Basic · Object Innovations Course 4235 Student Guide Revision 2.0 Windows Presentation Foundation Using Visual Basic

WpfVb Chapter 9

Rev. 2.0 Copyright © 2008 Object Innovations Enterprises, LLC 324 All Rights Reserved

</Window.Resources> ... 8. Now you can remove the entire TextBox.Background element from all three

textboxes and include the Background as a property, using the StaticResource markup extension to reference the newly added boxGradient resource.

<TextBox Margin="10" Width="72" Name="txtOp1" BorderBrush="{StaticResource boxBorders}" Background="{StaticResource boxGradient}" > </TextBox> 9. Build and run your application. Now you are finished improving your application to

use resources correctly!