ptg7068940
i
Rebecca M. Riordan
Fluent
Visual Basic
®
ptg7068940
ii
Fluent Visual Basic
©
Copyright © 2011 by Rebecca Riordan
All rights reserved. No part of this book shall be reproduced, stored
in a retrieval system, or transmitted by any means, electronic,
mechanical, photocopying, recording, or otherwise, without written
permission from the publisher. No patent liability is assumed with
respect to the use of the information contained herein. Although
every precaution has been taken in the preparation of this book,
the publisher and author assume no responsibility for errors or
omissions. Nor is any liability assumed for damages resulting from
the use of the information contained herein.
ISBN-13: 9780672335808
ISBN-10: 0672335808
Library of Congress Cataloging-in-Publication Data is on file.
Printed in the United States of America
First Printing November 2011
Trademarks
All terms mentioned in this book that are known to be trademarks or
service marks have been appropriately capitalized. Sams Publishing
cannot attest to the accuracy of this information. Use of a term in
this book should not be regarded as affecting the validity of any
trademark or service mark.
The Windlass Lowercase and Brandywine fonts are copyrights of the
Scriptorium foundry, www.fontcraft.com.
Wa r n i n g and Disclaimer
Every effort has been made to make this book as complete and
as accurate as possible, but no warranty or fitness is implied. The
information provided is on an “as is” basis. The author and the
publisher shall have neither liability nor responsibility to any person
or entity with respect to any loss or damages arising from the
information contained in this book.
Bulk Sales
Sams Publishing offers excellent discounts on this book when
ordered in quantity for bulk purchases or special sales. For more
information, please contact
U.S. Corporate and Government Sales
1-800-382-3419
For sales outside of the U.S., please contact
International Sales
Associate Publisher
Greg Wiegand
Signing Editor
Neil Rowe
Managing Editor
Kristy Hart
Project Editor
Andy Beaster
Indexer
Cheryl Lenser
Proofreader
Karen Gill
Technical Editor
John Hardesty
Publishing Coordinator
Cindy Teeters
Cover Designer
Gary Adair
Composition
Rebecca Riordan
ptg7068940
Acknowledgements
Yes, I know it says “Rebecca M. Riordan” on the cover, but that’s not really
true. Without the assistance of some amazing people, this book would never have
made it out of my head, much less into your hands. So, in order of appearance, I
would like to thank:
Neil Rowe, my editor, who took a chance on a very different way of writing
computer tutorials. Without Neil’s leap of faith, Fluent Learning would never have
happened. My technical reviewers, David Sceppa, Eric Weinburger
and John Hardesty, who collectively caught an embarassing number of code
typos and I-knew-what-I-meant obscurities. Finally, my copy editor, Karen
Gill, who not only made sure the language in the book resembles English, but also
expressed an unexpected and greatly appreciated enjoyment in the project. (Any
remaining errors and infelicities are, of course, my responsibility.)
Jake von Slatt of The Steampunk Workshop (steampunkworkshop.com),
Samantha Wright (samantha-wright.deviantart.com) and Mindbloom
(mindbloom.com) were all gracious enough to allow me to use their images. These
are all seriously cool people, folks. I can’t urge you strongly enough to go explore
their sites.
iii
ptg7068940
iv
Getting Started
Introduction . . 1
Fluent Learning Because
This book isn’t for everyone
What you’ll learn
What you’ll need
How it works
Application Development . . 9
The development process
System design
Creating executables
The .NET Platform . . . . . . . .43
.NET Components
Say hello
Say what?
The Visual Studio UI 67
Solutions, projects and stuff
Take control
Get some help
Testing & Deployment . . . . .93
Errors & exceptions
Deployment
The Language
Part 1: Nouns . . . . . . . . . . . .121
Statements
Declared elements
Comments
Directives & Attributes
Part 2: Transitive Verbs . . .155
Literal expressions
Object expressions
Part 3: Intransitive Verbs . . 181
Control of flow commands
Exception handling commands
The .NET Framework Library
Classes in the .NET Framework . 221
The Class Designer
Class definitions
Fields & properties
Methods
Other Framework Types . . . . . . . . 269
Structures
Enumerations
Interfaces
Wo r k i n g w i t h t y p e s
The Class Library, Part 1 . . .305
Namespaces
The Object Browser
Numeric data
Character data
Times & dates
The Class Library, Part 2 . . .349
Arrays
Specialized Sets
Generics
Discover the secret to efficient
programming: The best code is the
code you don’t have to write yourself.
Learn how to speak Visual
Basic. It’s a language, much
like English, Spanish or Latin,
only simpler.
Find out what this whole “being a
programmer” thing is all about and
how to use the tools you’ll need to
build applications.
ptg7068940
v
best practice
OOA & D . 381
Type relationships
OOP principles
Type mo difiers
Programming Principles . . . . 425
The Single Responsibility Principle
The Open/Closed Principle
The Liskov Substitution Principle
The Law of Demeter
Patterns . . . . . . . . . . . . . . . . . .457
The Strategy Pattern
The Observer Pattern
Architectural Patterns
wpf
XAML . . . . . . . . . . . . . . . . . .501
Fundamentals
WPF types
XAML & Visual Basic
WPF Controls . . . . . . . . . . 531
WPF panels
Control classes
Content controls
Items controls
Dependency Properties . . . 591
The basics
Creating dependency properties
WPF Interactions . . . . . . . . 627
Routed events
WPF Commands
WPF Graphics . . . . . . . . . . 669
Color
Brushes
Pens
Typo graphy
Effects
Resources . . . . . . . . . . . . . . . 719
Resource dictionaries
Styles
Property triggerrs
Event triggers
Templates . . . . . . . . . . . . . . .765
Building controls
Building control templates
The VisualStateManager
WPF Binding . . . . . . . . . . . .797
Creating bindings
Binding to collections
Wo r k i n g w i t h c o l l e c t i o n s
Put all you’ve learned to good
use by learning how to use
Microsoft’s latest and greatest
interface platform.
Stand on the shoulders of the
experts by learning the best
programming practices and how
to implement them.
Contents
ptg7068940
vi
Tell Us What you think!
As the reader of this book, you are our most important critic
and commentator. We value your opinion and want to know
what we’re doing right, what we could do better, what
areas you’d like to see us publish in, and any other words of
wisdom you’re willing to pass our way.
As a Executive Editor for Sams, I welcome your
comments. You can fax, email, or write me directly to let
me know what you did or didn’t like about this book
—as
well as what we can do to make our books stronger.
Please note that I cannot help you with technical problems
related to the topic of this book, and that due to the high
volume of email I receive, I might not be able to reply to
every message.
When you write, please be sure to include this book’s title
and author as well as your name and email address, phone,
or fax number. I will carefully review your comments and
share them with the author and editors who worked on this
book.
Email:
Fax: 317-428-3310
Mail: Neil Rowe, Executive Editor
Sams Publishing
800 East 96th Street
Indianapolis, IN 46240 USA
ptg7068940
1
Welcome! I’m so glad you stopped by.
This book doesn’t look much like other technical tutorials, does it? Well, for
once, looks aren’t deceiving, because Fluent Learning books aren’t much like
other technical tutorials. We don’t want to teach you things.
We want to help you learn things. We’ve done a lot of research into
how people learn, and it turns out that talk, talk, talking at you (like most books do) isn’t wrong,
exactly, but it makes learning harder than it needs to be.
Did you learn to speak your native language by reading a book? Of course not; that’s not how
people learn. You heard people speaking, tried it for yourself, and then corrected yourself when
other people pointed out your mistakes. Sure, you studied grammar and learned new words
in school, but the basics (“More milk, Mommy”) you learned by yourself. Now,
barring accident and illness (or one-too-many mojitos), you’re not likely to forget it, are you? And
you don’t have to think about the mechanics of speech, just what you want to say.
That’s really how we learn everything. We gather some initial
information, practice, correct our mistakes, and then add to our basic
knowledge. That’s not what happens in most tutorials, but that’s
how Fluent Learning works. I’ll give you enough
information to get started, give you some exercises to
figure out how to do something, and then
elaborate on what you’ve learned. Simple,
natural, and if you do the work, you
will learn. Soon you’ll be able to concentrate
on what you want to do, not how to do it, just
like when you learned to speak. (But it won’t
take as long as learning to speak well.)
ptg7068940
2
Put on your thinking hat…
You have a messy stack of
papers and a spool of wire.
What can you do?
public String Message;
On your own
Objects instantiate classes. That is, they are instances of them. The
statement below contains both a class and an object. Which do you think
is which?
Fluent Learning Because…
We Want to Learn, not
listen
Our minds like to learn anything the way
we learned our native language: by trial &
error. Instead of reading a lot of words, you’ll
do a lot of exercises. Real exercises, that
make you think, not walkthroughs that tell
you what to type. (But we’ll have a few of
those, too.)
We want to work, not pass tests
You want to be able to apply what you learn in the real world, not just pass
a test on the subject. To help you do that, the On Your Own exercises
invite you to make those connections as part of the learning process.
ptg7068940
3
We don’t live in a world of words
Our minds absorb information through all our senses, not
just speech. We’ll use graphics, context and rhythmic
language to appeal to sight, touch and sound.
We think in patterns, not straight lines
Our minds work best with patterns, not individual facts. We’ll
always present new ideas in context to help you understand how
all the pieces fit together.
We want a map, not a mystery
Our minds are constantly evaluating progress, but
that’s not possible unless we know where we’re
going. We’ll use lots of signposts so you always
know where you are and where you’re headed.
We’re artists, not freight trains
Our minds don’t chug along from point A to point
B on a single track. Like any artist, we start with
a sketch and then fill in the details. Rather than
presenting all the information about a topic at one time,
we’ll start simply and add the details as you have
more context. That way they’ll stick.
ptg7068940
4
This book is for you if:
• You don’t know anything (or at least not
much) about programming but want to
learn.
• You’ve been using a computer for awhile
but don’t really know how applications
get written.
• You’ve done a little playing around with
Visual Studio and Visual Basic but don’t
really feel comfortable about your skills.
It’s scary not knowing what you don’t
know, and this book can help with that.
This book probably isn’t for you if:
• You don’t know how to use a computer
at all. I assume that you know how to do
things like opening applications, clicking
buttons and choosing items from menus,
so if you don’t know that yet, you might
want to start with a basic book on using
Windows and come back to this one
later.
• You know a version of VB, but haven’t
used it in awhile and want to brush up
your skills. This book isn’t well suited to
browsing and skimming.
This book isn’t for everyone
I really hate it when technical books announce that they’re for “everyone”, don’t you? It can’t possibly
be true, and saying that it is doesn’t sell any more books in the long run. It just irritates people who get
confused (because the book’s too advanced for them) or bored (because the book’s too basic). I don’t want to
irritate or bore you, so I’ll say it plainly: This book isn’t for everyone.
This book might be for you if:
• You’re a Visual Basic 6 programmer and want to learn Visual Basic .NET starting with
the basics.
• You’re a Visual Basic 6 programmer and want to learn to build WPF or Silverlight
applications in Visual Basic .NET. There are lots of WPF/Silverlight tutorials around,
and some of them are very good, but most of them assume you know C#. If you don’t,
this might be a good introductory book for you.
• You’re a beginning Visual Basic programmer and want to learn patterns & best
practices. There are books around that specialize on that subject, but they tend to be
pretty advanced, so you might find this book more comfortable.
ptg7068940
5
What you’ll learn
You and I both know that you won’t be an expert Visual Basic programmer after reading one book, no
matter how good it might be. You won’t be an expert after reading two books, or three, or a dozen. Of
course you should read what the experts have to say. But the only way to build real expertise is to write
a bunch of applications, make a bunch of mistakes, and fix them. It takes time and experience, and I can’t
give you that. But I can get you started.
after you finish this book you will:
• Understand the structure of the Visual Basic language, its basic syntax, expressions and
commands.
• Understand the role that the .NET Framework plays in application development.
• Know the basics of the .NET Framework core types and how to use them.
• Have a working knowledge of designing object-oriented applications using design
principles and patterns that will let you not just program, but program
well
.
• Have a working knowledge of the common design patterns used to develop modern
applications.
• Have a working knowledge of the XAML declarative language.
• Understand how to write attractive, useful applications in Windows Presentation
Foundation.
• Be ready to move on to more advanced books on specific programming topics.
• Be ready to start writing applications and figuring the rest out for yourself.
but you won’t:
• Know everything there is to know about how the Visual Basic compiler or the CLR
works. (I’m not sure anyone does.)
• Know every nook and cranny of the Framework Class Library. (But you will know
how to explore it.)
ptg7068940
6
What you’ll need
You don’t need much to get started. This book, of course. (You did buy this copy, didn’t you?) And a
copy of Visual Studio. You’ll also need something to write with, because not all of the exercises are done at
the computer, and you might want a notebook of some kind if you don’t like writing in books.
getting visual studio
There are several different levels of Visual Studio. If you’ve already bought and installed
a copy, you’re good to go. If you haven’t, you can use the free Visual Basic .NET Express
edition. Yo u can download it from the Microsoft We b site. Here’s what you need to do
on the day I’m writing this, but Microsoft has been known to move things around, so be
forewared: Yo u may have to hunt around a bit.
1. From the main Microsoft We b site, choosing Visual Studio from the Products menu
will take you to the Visual Studio home page.
2. Choosing Express from the list of products at the top of the page will take you to the
Express versions page.
3. Choosing Visual Basic 2010 Express on the home page will take you to the product
page. Choosing Download on the left side will take you to the Download page, where
you can download an ISO image or install directly from the We b .
Getting the source code
Yo u won’t need to download the source code in order to do the exercises in this book,
but it’s available on the We b at informit.com/title/9780672335808.
ptg7068940
7
How it works
If you’ve read this far, you already know that you’re not going to be able to just sit back and listen to
me talk at you. The core of this book is the exercises, and if you’re going to learn, you’ll need to work
through them. Really do them. You can’t just think about the answers, You need to sit down at the
computer or pick up your pencil and do the work. Here’s a taste of some of the things you’ll be doing:
The thinking hat
Most of the exercises in the book tell you to Put on Yo u r Thinking
Hat. I’ll give you answers to these exercise, but it’s really important to
understand that you won’t always get the answers completely right, and
that’s okay. It doesn’t mean you’re not “getting it”. It means that I don’t
always play fair, because you learn as much (or more) from your mistakes.
On Your Own
Some exercises ask you to do things on your own, and I won’t
give you the answers. Sometimes there really aren’t answers;
they’re just things you need to think about. It might be tempting
to put these aside for “later”, but it’s best if you don’t. They’re
part of the learning process.
Take a break
From time to time I’ll suggest that you take a break before you move on
to the next section. Of course you can take breaks whenever you like, but
these suggestions aren’t because I think you might be getting tired. I make
these suggestions because learning research tells us that if you stop for
15 minutes or so before you review, you’re much more likely to transfer
information to long-term memory. (In other words, you’ll actually learn
it.)
ptg7068940
8
ptg7068940
9
Application
Development
So, you want to learn to program. That’s great. You’re reading the right book. But what
exactly is programming? Is it the same as software development?
And what about that other stuff you might have heard about development platforms,
application architectures, development methodologies, design patterns, best practices. It all starts to
sound a little scary, doesn’t it?
In this chapter, we’ll figure out what all these things are, and where they all fit in the
process of getting from here (an idea for some software) to there (a working application).
Relax. It’s not as complicated as you think
Put on your thinking
hat…
You have a messy stack
of papers and a spool of
wire. What can you do?
Chapter 01 - Application Development.indd 9 9/29/2011 10:12:05 AM
ptg7068940
10
A project begins when
someone has an
idea
.
The idea gets translated
into a
specification
.
The
specification
tells the
programmer what the system
needs to do.
The software executes in a specific
runtime environment
, like
Windows or a browser.
When people use
your software,
they’ll often come
up with new
ideas and the
project starts all
over again!
ptg7068940
11
The
development environment
provides the tools to turn the source code
into working software.
Using the specification, a programmer creates
source code
in a programming language
like Visual Basic.
ptg7068940
12
hOW’D YOU DO?
I gave you a messy stack of paper and spool of
wire. Thinking Cap exercises don’t always have
a single right answer, but here are two things you
might have done
So what’s the point here? That in application development the right answer is
almost always
“it depends”. The best solution will depend on how the
application is going to be used. It will depend on how much time and effort are
available (or you’re willing to invest). It will depend on what else is going on in the
application.
The best solution depends on well, it depends.
You might have bound the papers
into a notebook. That’s a good
permanent solution, but a lot of work.
Or you might have simply
made a paperclip. Easy and
fast, but probably temporary.
ptg7068940
13
Let’s review that process
Start with a good idea (that’s the hard part!), and you’re just five steps away from a solution. In this book
we’ll mostly be looking at how you write source code, but don’t worry, we’ll look at the rest of the steps
too at least enough to get you started on the right path.
…and then create a
specification.
Use best practices…
…to create the source code.
Create an executable…
…to run in your chosen
environment.
Start with a good idea…
What’s this stuff? These images represent
system architectures, development
methodologies, and best practices. These
are the principles that make the difference
between code that just works (mostly), and a
reliable, maintainable application. They’ll save
you money and headaches down the road,
and we’ll talk about them in detail in this
chapter and throughout the book
ptg7068940
14
Meet Neil & Gordon
Before we get started, I’d like you to meet the clients we’ll be working with. They run the hottest new
cafe in town. But they’re drowning in their own success. There’s so much to manage! Schedules, menus,
meetings, and now that their business is growing, they need to get all those yummy recipes out of their
heads and into a useable form. The boys are geniuses in the kitchen, but they don’t know where to start
with this management stuff.
We’ll be helping them out throughout the book.
ptg7068940
15
System design
We k n o w t h a t t h e d e v e l o p m e n t p r o c e s s b e g i n s w i t h a n i d e a t h a t g e t s
translated into a specification that describes what the system is to do.
We ’ l l s t a r t , t h e n , b y l o o k i n g a t a f e w t o o l s f o r c a p t u r i n g t h e s y s t e m d e s i g n .
The development process
Everything we do fits into the context of the process of a whole, so we
need to understand that first.
Creating Executables
The integrated development environment (IDE) provides the tools that
translate source code into an executable, a piece of software that a user
or another piece of software can execute. We’ll be using Visual Studio
to create executables, and before we can make decisions about how to
structure an application, we need a little more detail about how that works
in the context of the .NET Framework.
On Your Own
Do you have some ideas about applications you’d like to write? Make a
note of three or four of them. We’ll come back to them again and again.
Task List
In the rest of this book we’ll go into detail about step 3 of the development
process: writing code, and writing it well. But there are three things we need to
examine first:
ptg7068940
16
The Development Process
The application development process begins when somebody needs
a computer to do something. That “something” might be a change to
an existing piece of software or a completely new system, but most
applications are (or should be) developed in response to a need.
The “something” that the application is to do is captured in a
specification. A specification can be as simple as a diagram scribbled on
a napkin or many volumes of detailed description. It might be “complete”
before any code gets written, or it might be developed over the course of
the project.
Yo u ’ l l u s e t h e s p e c i fi c a t i o n t o d e v e l o p t h e a p p l i c a t i o n . I n d o i n g s o ,
you’ll choose an effective development methodology (the set of steps
you’ll perform during development) and be guided by best practices
(rules of thumb that experience has shown result in more efficient and
maintainable code). You may also implement design patterns, which are
standard solutions to common programming problems.
ptg7068940
17
one more time
“Programming” is largely (but not only) a matter of writing source
code. That means, for us, writing Visual Basic statements and using the
functionality provided by the .NET Framework. As you’ll see, the .NET
Framework does a lot of the work for us.
Most programmers use an integrated development environment (ide)
that combines a text editor (the bit that lets you type stuff), a compiler
(the bit that translates your source code into object code, instructions
that can be understood by the computer), a linker (the bit that combines
bits of object code into an executable), and other useful tools like testers
and visual designers. Like most Visual Basic programmers, we’ll be using
Microsoft Visual Studio, and we’ll look at all these functions throughout
this book.
Once the application is written and compiled into an executable, it
operates in a specific runtime environment. In this book we’ll be
developing applications that run under Microsoft Windows, but you
should know that Visual Basic and Visual Studio can be used to write for
several different platforms, including the Web and mobile devices.
take a break
That’s the first task done! Now would be a good time to take a
short break and relax a bit before you come back to the rest of the
chapter.
ptg7068940
18
Review
Before we move on, let’s do one last exercise to make sure you’ve got the process down
pat. The icons below are out of order. Number them correctly, and then describe each
step.
ptg7068940
19
System Design
What’s the difference between the sound my cat makes walking on the piano and the
sounds made by a concert pianist? A plan.
When you’re programming, the plan you work with is a specification. (You knew that, right?)
Here are some things you need to know about specifications:
• There’s no single right way to prepare
one.
• The detail required is determined by
the complexity of the application and
your experience. You’ll need to go into
more detail when the subject or the
functionality is new to you.
• Best practice dictates that the detailed
specification be developed during
the course of the project, but that
isn’t always possible. Sometimes your
client (or your boss) wants a complete
specification before you start coding. Be
prepared; either way requirements
will
change during the course of the project.
• Most nontrivial specifications will
include a lot more than the use cases
we’ll discuss here: database schemas,
screen layouts, architectural and
processing diagrams the details will
depend on the application. (Remember:
it depends.) But this isn’t an application
design book, so we’re just going to talk
about a few design tools that will get you
started. (We’ll look at a few others in
later chapters.)