This document discusses Silverlight programming and design. It covers separating graphical design from programming tasks using tools like Expression Blend and Visual Studio. It discusses the Metro design style used in Windows Phone development and how Silverlight supports adhering to this style. It also covers object-oriented programming concepts like classes, properties, and data binding as well as how XAML is used to describe Silverlight user interfaces.
In this chaper we will learn how to change the BackColor property of an object
Understand Visual Basic 2010 code statement formatsand see how IntelliSense can be used to enter code statements.We will discuss the Visual Basic programming languge syntax and write coding statements. We will also see how to correct coding errors in Visual Basic 2010.
Correct errors in Visual Basic 2010 code. We will learn how to print code and how to prepare an Event Planning Document.
Software engineering modeling lab lectures
engineering+ education purpose
This series of lectures was prepared for the third class of software engineering / Aliraqia University/ Baghdad/ Iraq.
In prepared these lectures, I depend on the YouTube to make it, the programs of the lectures are designed and executed by vb.net, discussions are also found here
These lectures are not finished yet, i will improve it in the future
Forgive me for anything wrong by mistake, I wish you can profit from these lectures
My regard
Marwa Moutaz/ M.Sc. studies of Communication Engineering / University of Technology/ Bagdad / Iraq.
about visual basic
visual basic 6.0 v/s other version
visual basic programming
form in visual basic
objects in visual basic
important controls
visual basic statement
loop statement
conditional loop
do until loop
In this chaper we will learn how to change the BackColor property of an object
Understand Visual Basic 2010 code statement formatsand see how IntelliSense can be used to enter code statements.We will discuss the Visual Basic programming languge syntax and write coding statements. We will also see how to correct coding errors in Visual Basic 2010.
Correct errors in Visual Basic 2010 code. We will learn how to print code and how to prepare an Event Planning Document.
Software engineering modeling lab lectures
engineering+ education purpose
This series of lectures was prepared for the third class of software engineering / Aliraqia University/ Baghdad/ Iraq.
In prepared these lectures, I depend on the YouTube to make it, the programs of the lectures are designed and executed by vb.net, discussions are also found here
These lectures are not finished yet, i will improve it in the future
Forgive me for anything wrong by mistake, I wish you can profit from these lectures
My regard
Marwa Moutaz/ M.Sc. studies of Communication Engineering / University of Technology/ Bagdad / Iraq.
about visual basic
visual basic 6.0 v/s other version
visual basic programming
form in visual basic
objects in visual basic
important controls
visual basic statement
loop statement
conditional loop
do until loop
In this class session, objects and classes are introduced along with a definition of what object orientated programming is. Addition topics that are covered include instantiation, reuse, encapsulation, and inheritance.
This presentation is a part of the COP2272C college level course taught at the Florida Polytechnic University located in Lakeland Florida. The purpose of this course is to introduce students to the C++ language and the fundamentals of object orientated programming..
The course is one semester in length and meets for 2 hours twice a week. The Instructor is Dr. Jim Anderson.
These projects demonstrated my ability to program Visual Studio .Net with C# as the programming language in 2 separate projects.
The Purpose of the first project was to build parts of the business tier for a retail Company. The goal is to create and test two assemblies. The first assembly is a class library project called Foundation. It will contain various interfaces and base classes.
The second assembly is also a Class Library project and its called AppTypes and it will contain various entity, collection and exception classes used by various business processes.
The Objective of the second project Is to create a database to support the principal functions of a library’s day-to-day operations: adding new members (adult and juvenile) and checking books in and out.
A Windows Forms-based front end application that will provide a librarian with a visual interface through which he or she may perform the desired functions.
And the project goal is to Design and develop a front end application that satisfies the four basic functionalities: Add Adult, Add Juvenile, Check in a book, Check Out a book.
Develop code that is easily maintainable.
Provide validation for all required fields.
Provide adequate error handling.
Produce a user interface that is intuitive, requiring minimal training for users while minimizing resource utilization.
If you want to develop web based, desktop or mobile applications using ASP, then Visual Studio .NET is the place for you. It provides a complete set of developmental tools for developing the various applications.
VB.Net, .Net Framework, Visual Studio(Forms and console base application) programs
Shivangi Chaurasiya From Thakur Polytechnic
Studying in Diploma in 3rd Year (2020-2021)
Design Patterns : The Ultimate Blueprint for SoftwareEdureka!
Object Oriented Programming is one of the biggest evolution ever happened to the software industry. Lots of languages started implementing OOP concepts thinking it would add lot of value and will improve the adaptability of the languages. While the OOP provides the concepts, programming languages still lack the essence that is needed for better software design. Design patterns fill the gap by providing solution templates for commonly occurring design problems. As any other software entity, Design Patterns is an evolving subject and it has reached its extreme maturity now by covering most of the design problems that the current software industry is facing. Practicing design patterns has helped the success ratio of software projects these days immensely. Design patterns have become a magic wand in the hands of successful software programmers and architects.
Windows azure: Introducción a la Nube y HoL de Azure MICTTMICTT Palma
Introducción a la nube
Fundamentos de Windows Azure
Windows Azure
AppFabric
SQL Azure
Dallas (Marketplace)
Desarrollo sobre Windows Azure
Hands-on Labs
Crear una suscripción (gratuita)
Windows Azure: introducción al servicio de ejecución
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
The Art Pastor's Guide to Sabbath | Steve ThomasonSteve Thomason
What is the purpose of the Sabbath Law in the Torah. It is interesting to compare how the context of the law shifts from Exodus to Deuteronomy. Who gets to rest, and why?
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
Palestine last event orientationfvgnh .pptxRaedMohamed3
An EFL lesson about the current events in Palestine. It is intended to be for intermediate students who wish to increase their listening skills through a short lesson in power point.
Model Attribute Check Company Auto PropertyCeline George
In Odoo, the multi-company feature allows you to manage multiple companies within a single Odoo database instance. Each company can have its own configurations while still sharing common resources such as products, customers, and suppliers.
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
The French Revolution, which began in 1789, was a period of radical social and political upheaval in France. It marked the decline of absolute monarchies, the rise of secular and democratic republics, and the eventual rise of Napoleon Bonaparte. This revolutionary period is crucial in understanding the transition from feudalism to modernity in Europe.
For more information, visit-www.vavaclasses.com
How to Create Map Views in the Odoo 17 ERPCeline George
The map views are useful for providing a geographical representation of data. They allow users to visualize and analyze the data in a more intuitive manner.
Ethnobotany and Ethnopharmacology:
Ethnobotany in herbal drug evaluation,
Impact of Ethnobotany in traditional medicine,
New development in herbals,
Bio-prospecting tools for drug discovery,
Role of Ethnopharmacology in drug evaluation,
Reverse Pharmacology.
3. Silverlight 4 Business Applications Media Beyond the Browser Silverlight 1 Silverlight 2 Silverlight 3 Silverlight 4 September 2007 October 2008 July 2009 April 2010
4. Programming and Design Software and Design It is a sad fact that most programmers are not very good at graphic design Although some are (lucky people) Also, most designers do not program much
5. Programming and Design Separation of tasks One way to get good looking programs is to separate the graphical design aspects from the programming The designer can work on the look and feel of the application The programmer can implement the required behaviours Silverlight supports this way of working
6. Programming and Design Tools for the job : Graphical Design A Silverlight designer can use the “Expression Blend” to specify the appearance of the user interface A version of Blend for the phone is supplied as part of the phone SDK
7. Programming and Design Tools for the job : Code Creation A Developer can take the user interface design and use Visual Studio build the program to make it work Windows Phone developers use Visual Studio
8. Programming and Design The Metro design style The Windows Phone team have taken a lot of trouble over the look and feel of the phone They have created a design style, “Metro” to express this Programs on the phone should reflect this style
9. Programming and Design Design Style and programming As programmers we probably start of just worrying about making the program work This is a very good place to start But in modern systems the “look and feel” of the user interface is very important No matter how good the code is, if the program is hard to use it will not be popular You should pay careful attention to user interface issues when making your programs
10. Programming and Design Silverlight and Metro To make life easier for us the Metro style is “baked in” to the Windows developer tools The default appearance, behaviour and fonts of the user elements all match the style If you want to find out more about Metro you can read the style guidelines for it
11. Programming and Design Silverlight and Us We are going to use the Silverlight designer in Visual Studio This can be used to create a good quality user interface that adheres to the Metro principles If you know any Graphic Designers it is worth getting them on your development team when you make a Marketplace application They can make your programs much more impressive
12. Programming and Design Software Objects In this study of C# we will see that we can create software objects to represent things We talk to our customer to establish their requirements and then identify elements that our software will manipulate We then create software classes which contain the data and behaviours For example, if we were creating a bank application..
13. Programming and Design Software Objects public classAccount{private decimal balance ;private string name ;public stringGetName () {return name; }public boolSetName (stringnewName){ {// Final version will validate the namename = newName; return true; }// Other get and set methods here}
14. Programming and Design Data members public classAccount{private decimal balance ;private string name ;public stringGetName () {return name; }public boolSetName (stringnewName){ {// Final version will validate the namename = newName; return true; }// Other get and set methods here} This is the data our bank account will hold: The name of the holder and the balance
15. Programming and Design Data members public classAccount{private decimal balance ;private string name ;public stringGetName () {return name; }public boolSetName (stringnewName){ {// Final version will validate the namename = newName; return true; }// Other get and set methods here} These are the behaviours the account provides
16. Programming and Design UsingtheAccountclass The bank program can create instances of the account class and use them to hold customer information Each instance of an account represents a particular customer The bank software calls methods in the Account class to work with the data in it Account rob = new Account();rob.SetName("Rob");
17. Programming and Design ObjectsOrientedDesign Object Oriented Design is a great way to manage complex projects It lets you break the solution down into manageable chunks It allows you to put off detailed implementation of the elements until you know what they need to do It allows you to test objects separately before they are incorporated into the product
18. Programming and Design The Silverlight Adding Machine This is a very simple calculator All it can do is add two numbers The user types the numbers into the text boxes and presses the equals button The answer is displayed at the bottom of the screen
19. Programming and Design Silverlight and Objects Silverlight is implemented using objects to represent the elements on a User Interface Each of the items on the screen of the application shown is graphical rendering of a software object
21. Displayelement data Each of the elements contains data elements that define how it appears on the screen Position on the screen Height and width Font colour and size etc.. These values are used by Silverlight when the display is drawn If these value are changed by the program the appearance of the element will change
22. Typespfelement The adding machine actually contains three different types of Silverlight display element TextBox Used to receive user input from the keyboard TextBlock Used to display messages to the user Button Used to cause events in the application
23. ClassHierarchies and Silverlight The elements will have some properties in common All will have a position on the screen and a height and width But there will be some properties that are specific to that element Only a TextBox needs to track the cursor position for user input A class hierarchy is a great way to implement this
24. Silverlight elementclasshierarchy The Silverlight class hierarchy is quite complex Everything is based on the FrameworkElement class which contains the fundamental properties of all elements There are many other classes
25. ClassHierarchies Using a class hierarchy for Silverlight elements has many advantages A particular set of element data only needs to be stored once, at the appropriate position in the hierarchy The display drawing system can treat them all display elements in exactly the same way We can add new Silverlight elements that extend the behaviour of existing ones
26. Silverlight and Code This means that to update the items on a display our program will be calling methods or updating properties on the appropriate software object The next time that object is drawn the Silverlight rendering system will use the new data values and the appearance of the object will change to match
27. Silverlight and Design When we design a user interface we set values to give the elements position and size We do not do this from a program that we write (although we could) Instead we are going to use the design tools in Visual Studio to set up the elements We are going to start by using the element toolbox and the design surface
28. The Toolbox and Designer Visual Studio provides a menu of Silverlight elements that can be placed on the display page You can do this by simply dragging the elements from the toolbox onto the page
30. Silverlight elementnames When you drag an element onto the page Visual Studio creates a new variable in your program These are declared in a special area of the project that Visual Studio looks after for you And you should not fiddle with this or bad things will happen However, you should always make sure that your variables have sensible names
31. Settingthename of anelement The default name of an element is not useful TextBox1, Button1 etc We want to have more meaningful names firstsNumberTextbox, EqualsButtonetc We can use the Properties window in Visual Studio to update the name of an element in our program
32. Settinganelement The name of an element is right at the top of the properties pane in Visual Studio To display the properties pane for an object, click on the object in the design surface The pane will usually be located at the bottom right of the Visual Studio display
33. Editingthename of anelement You can simply type in the new name for your element here Make sure that it is a valid C# variable name, or Visual Studio will complain When you navigate away from this textbox the name will change
35. Silverlight element properties We have seen that Visual Studio lets us manipulate the properties of the display elements We can drag them around the display page We can set values using the property pane Now we are going to consider how the properties actually from the perspective of C# To do this we have to revisit what properties are in C# classes 35
36. Properties in C# A program is made up of classes A class can contain data and behaviours The data is held in member variables The behaviours are provided by member methods When you design an application you decide what classes are required and the data and behaviours they have
37. Private and Public Data in a class is usually made private Methods are usually public You call methods to make changes to the data inside the class This means that all changes to data in the class is controlled Programmers love having control........
38. Managing Class Data We might decide to create a class called Accountto store information in a bank The Accountclass will have lots of data items that are stored about each customer Each of these items will map onto a data member of the class The programmer must then provide methods to get and set the values of the items
39. Bank accounts and data Perhaps our bank needs to store the age of the account holder Perhaps they are concerned about allowing very young people to draw out too much cash This information must be stored in the account It will be a data member within it
40. NameProperty public class Account{ private int age; /// rest of account here} The age value is a privatemember of the Accountclass To work with the age value we have to provide methods that are public
41. Using Get and Set methods publicclassAccount{privateint age;publicintGetAge() {returnthis.age; }publicvoidSetAge( intinAge ) {if ( (inAge > 0) && (inAge < 120) ) {this.age = inAge; } }}
42. Managing the Age CurrentAccounta = newAccount(); a.SetAge(21); When we want to control the age property we can call the SetAge method We can use the GetAge method to read the age of the account holder
43. Get and Set Methods Creating Get and Set methods is a standard programming pattern Frequently they will perform validation of incoming data and reject out of range values I have not added any validation to the set method yet Nobody with an age less than 8 or greater than 100 can have an account
44. Using Properties The C# language provides properties to make getting and setting data easier They do not make things possible that we couldn’t do before They must make the programs easier to write Properties are used extensively in Silverlight for display elements
46. Property Keywords The block of code after the get keyword is obeyed when the property is read by a program It must return a value of the property type The block of code after the set keyword is obeyed when the property is written Within the set block the keyword value means “The value being assigned to the property”
47. Using the Age Property Account s = newAccount ();s.Age = 21;Console.WriteLine ( "Age is : " + s.Age ); When a program uses a property it looks just like direct access to a data member The difference is that the get or set behaviours are used the blocks of code in the property are used This makes the code much tidier
48. Property validation Account s = newAccount ();intnewAge = 150;s.Age = newAge;if (s.Age != newAge ) Console.WriteLine ( "Age was not set" ); If the property uses validation it I up to the user of the property to make sure that an assignment worked correctly
49. Multiple properties for one value publicintAgeInMonths{get {returnthis.ageValue*12; }} This property only has a get method It provides a way of reading the age in months
50. Properties and Silverlight The items that we see in the properties Pane for an element are all C# properties When an assigning to an element property a program runs code inside a C# set behavior This might seem inefficient Accessing the data directly would be quicker But it is actually a necessary part of how Silverlight runs 50
51. Properties and Notification The set method in a Silverlight property has to do a lot more than just update the stored data This action will also trigger a display update for the screen Setting a property in a program also sends a notification to the program that the property is being changed This idea of using property changes to trigger events is one we will return to 51
52. Page Design with Silverlight We can design all our pages by dragging items onto the page, giving them a name and then setting their properties Visual Studio will create all the code behind the program to make this work You can set many properties of element s including colour, texture, transparency and even animation But this is best left to Graphic Designers 52
53. Review Visual Studio provides a complete design tool for creating and managing user interfaces A Silverlight display is made up of elements Each element is implemented by a C# class which is part of the element hierarchy Silverlight elements expose properties which allow programs (and Visual Studio) to determine their location and appearance on the display page 53
55. XAML and Silverlight A Silverlight application is made up of pages that contain elements These have properties that determine where they are, how they appear and what they can do in an application The Visual Studio tool allows us to manipulate the page content by using the design surface and the element properties pane 55
56. Expressing Silverlight Elements The description of the elements in a Silverlight application is actually held in a text file This file is formatted in a particular way Microsoft invented a language, XAML to hold this design information: eXtensibleApplication Markup Language XAML was invented to hold user interface design information 56
57. Why do we need XAML? XAML allows us to separate the role of graphic designer and programmer The designer should not have to see code objects to work The programmer should not be held back while the design is produced The XMAL file provides a separation between the code that drives the application and the way the application looks 57
58. XAML file content <TextBox Height="72"HorizontalAlignment="Left" Margin="8,19,0,0" Name="firstNumberTextBox" Text="0"VerticalAlignment="Top" Width="460"TextAlignment="Center" /> This snippet of XAML is the description of the firstNumberTextBox in our adding machine It contains fields that describe the position and size of the textbox This file is managed by Visual Studio as your program is being developed 58
59. XAML in Visual Studio The XAML file holds the information which is updated by both views 59
60. The XAML language XAML is a “declarative” language It just tells us about things, it does not tell us what they do and how they can do it The XAML file has a particular format The characters < and > are used to mark the start and end of some elements in the file The format looks a bit like XML eXtensible Markup Language 60
61. Using XAML You can actually edit the XAML text in your project to create new display elements and modify existing ones This can often be much quicker than using the editing interface provided by Visual Studio You just have to type the new values into the XAML window and the properties of the element are changed immediately 61
63. The XAML file at run time When a Silverlight program runs the XAML file is compiled into a set of low level display instructions that are obeyed by the Silverlight runtime system This is the point at which the XAML object descriptions in the text are converted into program objects we can use in our code This all happens automatically as far as we are concerned 63
64. XAML and XML XAML looks a bit like XML XML means “Extensible Markup Language” This means that XML is really a way of designing languages that want to talk about something Just like the english language lets us invent verbs and nouns and put them into sentences that have meaning in a particular context 64
65. Inventing our own XML <?xml version="1.0" encoding="us-ascii" ?> <HighScoreRecordscount="2"> <HighScore game="Breakout"> <playername>Rob Miles</playername> <score>1500</score> </HighScore> <HighScore game="Space Invaders"> <playername>Username</playername> <score>4500</score> </HighScore> </HighScoreRecords> This XML format to hold a video game high score table 65
66. HighScore element <HighScore game="Breakout"> <playername>username</playername> <score>1500</score> </HighScore> The HighScore element contains two other elements, playername and score It also has a property that gives the name of the game We could add others, for example the date and time the score was achieved 66
67. HighScoreRecords element <?xml version="1.0" encoding="us-ascii" ?> <HighScoreRecordscount="2"> <HighScore game="Breakout"> <playername>username</playername> <score>1500</score> </HighScore> <HighScore game="Space Invaders"> <playername>username</playername> <score>4500</score> </HighScore> </HighScoreRecords> The HighScoreRecords element contains a count of the number of HighScore elements 67
68. XML and data structures We can invent our own language format whenever we have some structured data that we want to store The designers of XAML have done this They have created a language that lets us design user interfaces 68
69. The XAML data revisited <TextBox Height="72"HorizontalAlignment="Left" Margin="8,19,0,0" Name="firstNumberTextBox" Text="0"VerticalAlignment="Top" Width="460"TextAlignment="Center" /> We can see that the XAML content that describes a textbox is very similar to a HighScore element The designers of XAML had to work out what data fields are required in a TextBox object 69
70. What is a Markup Language? The “ML” in XML stands for “Markup Language” A markup language was originally a set of commands for the printers of a document ‘Put the words “Table of Contents” in bold’ When the World Wide Web was created the Hyper Text Markup Language was designed to allow a text file to describe a particular web page design 70
71. XML and HTML The idea of creating your own markup language was such a good one that people wanted a standard form for doing this XML came out of this drive for standards It is the way in which the files use the < and /> and other characters to mean the start and end of elements, names and properties It also tells you how to create “schemas” that define the structure and content of XML documents 71
72. XML Schema An XML schema describes a particular XML document format: “A HighScore element must contain a PlayerName and a Score value, but the Date value is optional” Programs can use a schema to make sure that a particular document contains content which is valid 72
73. XML and software XML allows programs to share data irrespective of what kind of system was used to create the data There are many software tools that can create schemas and you can even store the contents of C# directly into XML structured files However, for now just remember that the description of a Silverlight page is a text file containing an XAML document 73
74. XAML and Silverlight Pages A Silverlight application is made up of a number of pages Each page is expressed as a single XAML source file The page will contain descriptions of a number of Silverlight elements From time to time we will have to make changes to the XMAL file directly 74
75. Review The design of a Silverlight page is expressed as a XAML document stored as text file The separation of the design from the program code makes it much easier for designers and programmers to work together The format of a XAML document is based on XML (an eXtensible Markup Language) XML allows us to create languages that describe any kind of structured data 75
77. Silverlight and C# Up until now all we have done is create XAML designs for our application We have used the editing surface and the properties pane, along with a text editor Now we are going to see where the program content lives This code will provide the active content for our calculator This will work out the result 77
78. The Visual Studio Solution Explorer The Solution Explorer is another pane in Visual Studio It shows all the elements in a particular solution This includes all the application resources and XAML files 78
79. The MainPage.xaml file The MainPage.xaml file contains the XAML that describes how the main page looks If you add further pages to the application they will appear as xaml pages in the solution 79
80. The code behind a xaml page Each xaml page has a file of C# behind it We can find this by opening up the xaml file as shown in Solution Explorer 80
81. XAML file content namespaceAddingMachine{publicpartialclassMainPage : PhoneApplicationPage {// ConstructorpublicMainPage() {InitializeComponent(); } }} This is all the actual code behind our adding machine main page 81
86. Health Warning We have just had a quick look in the “engine room” of Silverlight This is somewhere you should never go Do not make any changes to this code or Visual Studio may get very upset and you will almost certainly break your program 86
87. Running our application We can run our application if we like We can type in values and press the equals button But nothing happens Next we need to make a method that will do the calculation and get it to run 87
88. calculateResult method privatevoidcalculateResult() { float v1 = float.Parse(firstNumberTextBox.Text); float v2 = float.Parse(secondNumberTextBox.Text); float result = v1 + v2; resultTextBlock.Text = result.ToString(); } This method will calculate the result and display it If we call this the display will be updated 88
89. Obtaining values privatevoidcalculateResult() { float v1 = float.Parse(firstNumberTextBox.Text); float v2 = float.Parse(secondNumberTextBox.Text); float result = v1 + v2; resultTextBlock.Text = result.ToString(); } This line gets the text out of the firstNumberTextbox and parses it to produce a floating point value 89
90. Calculating a result privatevoidcalculateResult() { float v1 = float.Parse(firstNumberTextBox.Text); float v2 = float.Parse(secondNumberTextBox.Text); float result = v1 + v2; resultTextBlock.Text = result.ToString(); } This statement calculates the result we get by adding the values together 90
91. Displaying the result privatevoidcalculateResult() { float v1 = float.Parse(firstNumberTextBox.Text); float v2 = float.Parse(secondNumberTextBox.Text); float result = v1 + v2; resultTextBlock.Text = result.ToString(); } This statement gets a string version of the result value and puts it into the result texbox 91
92. Silverlight elements and properties The method works because the Silverlight elements expose properties that the program can read (to get the numbers typed in) and write (to display the required result) Our program is able to work with the display elements because they are objects as far as we are concerned The objects are created when the program starts 92
93. Getting the result Now all we need is to run the calculateResult method when the Equals button is pressed To do this we have to connect an event generator (the button) with the method that will run when the button produces an event The event is generated when the user presses the equals button 93
94. Programs and events For events to work a program must have a way of managing an event as a data object We need to be able to give the button an object that represents a method to be called when the event occurs C# provides a delegate mechanism that can create references to methods Fortunately Silverlight and Visual Studio make this very easy to use 94
95. Events in Visual Studio We can ask Visual Studio to create an event delegate for us by double clicking on the element in the designer Visual Studio will do all the “plumbing” to make this work 95
96. The Event Handler Method When we have double clicked the button we find that there is now a new method in the MainPage class This will be called when the button is clicked in our program 96
97. Displaying the result privatevoidequalsButton_Click(objectsender, RoutedEventArgs e){calculateResult();} Visual Studio has given this method a sensible name This is based on the component name We just need to add a call of calculateResult to get the program to work 97
99. Managing Events The properties of a Silverlight element include information about the events and what methods they are bound to You can see this by selecting Events in the Properties pane 99
100. Events and XAML <Button Content="equals" Height="72"HorizontalAlignment="Left" Margin="158,275,0,0" Name="equalsButton"VerticalAlignment="Top" Width="160" Click="equalsButton_Click" /> We know that everything in Silverlight begins and ends with the XAML When we add an event binding in Visual Studio this adds a property to the XAML for that component You can see it above 100
101. Review Behind each XAML file is a C# source file that contains the behaviour for that page You add your own behaviours by putting methods into this code file If you bind Silverlight events to elements the event handlers are also placed in this file You connect these handlers to your code to produce a working application
Start Visual StudioOpen the AddingMachine project we created earlier.Open MainPage.XAML from the Solution Explorer if it is not already visible.Click on the top TextBox in the editing surface. This should cause the firstNumberTextBox to be selected in the MainPage.XAML file and the Properties pane to change to the details for firstNumberTextBox.Click in the MainPage.XAML file and move the cursor to the Height="72" property for this textbox. Change the value to 100. Tell the class to watch what happens in the designer. The textbox will change in height. Move to the Property pane and open the Layout item. This should now have the value 100. Type 72 into the layout information and show how the TextBox returns to its original height and the text in the XAML file returns to 72.Leave Visual Studio running and return to the presentation.
Start Visual StudioOpen the AddingMachine project we created earlier.Find MainPage.xaml in the Solution Explorer.Click to open it up and see the file MainPage.xaml.csDouble click this file to open it.Show the constructor method.Right click the name InitializeComponent in the method.Select “Go to definition” from the context menu.Show the code that creates the new instance of the objects on the screen.Make the point that the code we are seeing now was created by Visual Studio from the XAML.Run the program and note that all the buttons appear.Ask the class what would happen if you commented out the call of InitializeComponent.Comment out the method and run it again.The screen should be displayed as blank. Remove the comment and run the program again to show that we can get our components back.
Return to the AddingMachine projectShow that the MainPage.xaml.cs file just contains one method at the moment.Double click the button and note that we now have an event handler.Add the calculateResult method:private void calculateResult(){ float v1 = float.Parse(firstNumberTextBox.Text); float v2 = float.Parse(secondNumberTextBox.Text); float result = v1 + v2;resultTextBlock.Text = result.ToString();}Put a call of calculateResult in the event handler.Run the program and note that we can now do sums.Ask the class what would happen if we typed “Twenty five” into one of the text boxes.Run the program and note that an exception is thrown by the Parse method.Ask the class how they would fix this:Need an exception handler to capture the Parse exception. Or could use the TryParse method instead and test the result.When an error occurs we can tell the user Suggest a message box but I prefer turning the offending box red as this indicates there is an error without the user having to acknowledge the error by pressing any more buttons.