WP7 HUB_Diseño del interfaz con Silverlight

1,012 views

Published on

Fase 3.3

Published in: Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,012
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
2
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • Open the project in Demo 01 Broken Data validation using Visual StudioSelect Debug>Run to run the program.Enter in the value2 in the top window and 3 in the lower one.Press the equals button to perform the calculation.Note that the value 5 is displayed.Enter the value fred in the top window.Press the equals button to perform the calculation.Note that the text fred turns red.Ask the class if the program is now perfect.Answer: It isn’t. The text in the top TextBox will stay red for ever.Show this by changing the text fred to 99Press the equals button to perform the calculation.The result should be displayed, but the text will remain red.Ask the class how to fix this.Answer: Need to add an else behaviour to set the colour back to normal when the parse works.Close the project and return to the presentation.
  • Open the project in Demo 02 Working Data validation using Visual StudioSelect Debug>Run to run the program.Enter in the valuetwo in the top window and two in the lower one.Press the equals button to perform the calculation.Note that the error is displayed and both boxes turn red.Change the top value to 2Press the equals button to perform the calculation.Note that the error is still displayed, but the top box is now back to the normal colour.Change the bottom value to 2Press the equals button to perform the calculation.Note that the error goes away, and the correct answer is displayed.Close Visual Studio and return to the presentation
  • Open the project in Demo 03 Number Keyboard input using Visual StudioSelect Debug>Run to run the program.Click in the top TextBox and note that the keyboard has numbers on it.Click in the bottom TextBox and note that the numbers remain on the keyboard.Open the file MainPage.xaml and look at the XAML for TextBox2. Note that it has the InputScope defined.Make the point that TextBox1 doesn’t have this. Ask the class how this can still work?Answer: The InputScope property for TextBox1 is set in the constructor in MainPage.xaml.csOpen MainPage.xaml.cs and show the property being set.Close Visual Studio and return to the presentation
  • Open the project in Demo 04 Background asset as content using Visual StudioSelect Debug>Run to run the program.Show that the background is displayed.Use Windows to navigate to the folder Demo 04 Background asset as content\\AddingMachine\\Bin\\DebugShow that the folder contains a file called AddingGears.jpgMake the point that this is the image. Show that the assembly AddingMachine.dll is only around 14KLeave this folder openStop the programClose Visual StudioReturn to the presentation
  • Open the project in Demo 05 Background asset as resource using Visual StudioSelect Debug>Run to run the program.Show that the background is displayed.Use Windows to navigate to the folder Demo 05 Background asset as resource\\AddingMachine\\Bin\\DebugShow that the folder does not contain a file called AddingGears.jpgShow that the assembly AddingMachine.dll is now over 300K, since it now contains the image.Compare this folder with the one for Demo 04Stop the programClose Visual StudioReturn to the presentation
  • Open the project in Demo 01 AddingMachine with no button using Visual StudioSelect Debug>Run to run the program.Enter in the value2 in the top window and 3 in the lower one.Note that the value is displayed as the numbers are entered, and that there is no need to press the Equals buttonClose the project and return to the presentation.
  • Open the project in Demo 02 AddingMachine with data binding using Visual StudioEnsure the target device is set to Windows Phone EmulatorSelectDebug>Start Debugging to start the program running.Use Solution Explorer to open the file Adder.csPut a breakpoint on the statement in the set behaviour for TopValue:topValue = value;In the Windows Phone Emulator click in the top number TextBox and type the number 45 into itClick the background on the emulator to navigate away from the TextBox.The program will now hit the breakpoint that is in the AddingMachine class.Explain that this is because we have a Two Way binding with the control and this property. When the value changes the set method for our property is called.Rest the cursor over the value in the method to show that 45 is being supplied to the property.Press F10 or the Step Over button to step to the line:if (PropertyChanged != null)Ask the class if this condition is true or false?Answer: It will be true, as a Silverlight component has registered an interest in this class.Press F10 or the Step Over button to step into the conditional code.The execution should now be at the statement:PropertyChanged(this, new PropertyChangedEventArgs("AnswerValue"));Add another breakpoint to the statement in the getbehaviour for AnswerValue:return topValue + bottomValue;Press F10 or the Step Over button to step over the PropertyChanged code.This should cause the breakpoint in the get behaviour to fire.Ask why.Answer: The Silverlight elements that are bound to the PropertyChanged event have been told that the AnswerValue has changed.They are therefore going and getting a new version of the answer.Press F5 to allow the program to run on. Return to the emulator and show that the display has been updated.Clear the breakpoints (for next time)Close the project and return to the presentation.
  • Open the project in Demo 01 MultipageDemousingVisual StudioSelect Debug>Run to run the program.Press the Page 2 button and navigate to page 2.Press the Back button on the phone to return to the main page.Press the Page 3 button and navigate to page 3.Press the Back button and note how the confirmation message box appears.Stop the program.Close the project and return to the presentation.
  • Open the project in Demo 02 Data passing using Visual StudioSelect Debug>Run to run the program.Enter some text into the textboxPress the Page 3 button and navigate to page 3.Note that the text on the page is the same as that entered into the textbox.Stop the program.Close the project and return to the presentation.
  • Open the project in Demo 03 Shared Data using Visual StudioSelect Debug>Run to run the program.Enter some text into the textboxPress the Sub Page button and navigate to the second page.Show that the text has been copied over.Open the file MainPage.xaml.cs. Show that the class uses the OnNavigatedFrom event to copy the information into the application.Open the file SubPage.xaml.cs.Show the OnNavigatedToevent which loads the data.Stop the program.Close the project and return to the presentation.
  • WP7 HUB_Diseño del interfaz con Silverlight

    1. 1. User Interface Design with Silverlight<br />
    2. 2. Improvingtheuserexperience<br />
    3. 3. Topics<br />Manipulating Silverlight element properties<br />Editing the XAML for Silverlight elements<br />Using the MessageBox class<br />Adding and using assets<br />Assets as Content and Resources<br />
    4. 4. Silverlight Elements<br />At the moment we know about three elements<br />TextBlock to display messages and labels<br />TextBox to receive input from the user<br />Button to generate events<br />In this session we are going to improve our understanding of these elements to create more interesting user interfaces<br />4<br />
    5. 5. Elements as objects with properties<br />From a programming perspective we regard a Silverlight display element as an object<br />The object is an instance of the particular element type<br />We can call methods and set properties on the object<br />These can result in a change in the appearance of the object on the display<br />5<br />
    6. 6. TextBlock properties<br />resultTextBlock.Text = result.ToString();<br />To change the text displayed by a TextBlock we just have to assign a string to the Text property<br />Behind the property will be some code that runs when the property is assigned<br />This will tell Silverlight that the text has changed and will result in the display updating<br />We don’t have to worry about how this works<br />6<br />
    7. 7. Improving Error Handling<br />At the moment our AddingMachine program is not tolerant of user errors<br />If they enter text rather than a number into a TextBlock the Parse method will throw an exception and the program will halt<br />7<br />
    8. 8. Parse and Exceptions<br />float v1 = float.Parse(firstNumberTextBox.Text);<br />The Parse method will throw an exception if we give it invalid inputs<br />Our program must deal with this more gracefully than just stopping<br />8<br />
    9. 9. Using TryParse to detect errors<br />float v1 = 0;if (!int.TryParse(firstNumberTextBox.Text, out v1)) {// Invalid text in textbox}<br />The TryParse method will try to parse the string<br />The clue is in the name<br />If the parse fails it returns false<br />It will not throw an exception<br />9<br />
    10. 10. Using the out parameter<br />float v1 = 0;if (!int.TryParse(firstNumberTextBox.Text, out v1)) {// Invalid text in textbox}<br />TryParse is given a reference to the location where it must place the result<br />This is an out parameter<br />The method is passed a reference it can follow to put the result into v1<br />10<br />
    11. 11. Changing the colour of Text<br />float v1 = 0;if (!float.TryParse(firstNumberTextBox.Text, out v1)){firstNumberTextBox.Foreground = newSolidColorBrush(Colors.Red);return;}<br />This version of the number conversion code turns the colour of the text in the TextBox red if the number is invalid<br />11<br />
    12. 12. Drawing and Brushes<br />float v1 = 0;if (!float.TryParse(firstNumberTextBox.Text, out v1)){firstNumberTextBox.Foreground = newSolidColorBrush(Colors.Red);return;}<br />The text is drawn using a Silverlight brush<br />The simplest form of brush is a solid colour, but you can make bushes from images and gradients<br />12<br />
    13. 13. Demo 1: Faulty Number Validation<br />Demo<br />13<br />
    14. 14. Brush setup<br />privateSolidColorBrusherrorBrush = newSolidColorBrush(Colors.Red);privateBrushcorrectBrush = null; <br />This solution uses two brushes<br />One is set to the error colour, Red<br />The other is copied from the TextBox so that we can use it to put the colour back if the entry is valid<br />14<br />
    15. 15. Storing the correct brush<br />privatevoidcalculateResult(){boolerrorFound = false;<br />if (correctBrush == null) correctBrush = firstNumberTextBox.Foreground;// Rest of method goes here}<br />The first time the method is called it makes a copy of the brush used in the TextBox<br />15<br />
    16. 16. Proper Error display<br />privatevoidcalculateResult(){// Sort out brushes<br />if (!float.TryParse(firstNumberTextBox.Text, out v1)) {firstNumberTextBox.Foreground = errorBrush;errorFound = true; }else {firstNumberTextBox.Foreground = correctBrush; }}<br />The text is drawn using a Silverlight brush<br />The simplest form is a solid colour, but you can make bushes from images and gradients<br />16<br />
    17. 17. Demo 2: Working Number Validation<br />Demo<br />17<br />
    18. 18. Further Improvement<br />At the moment the text keyboard is displayed when the user starts to enter the numbers to be added<br />This is not what they would like<br />The number keyboard should be displayed first<br />18<br />
    19. 19. Editing the XAML for an element<br />The XAML is the part of the program that “declares” the Silverlight display elements that are used in the user interface on the page<br />We can modify the declaration to tell configure the TextBox to display the digital keyboard<br />This is the best place to perform such settings<br />Although you could also do this using C# code if you wanted to<br />19<br />
    20. 20. TextBlock XAML<br /><TextBox Height="72"HorizontalAlignment="Left" Margin="8,175,0,0" Name="secondNumberTextBox" Text="0"VerticalAlignment="Top" Width="460"TextAlignment="Center" /><br />This is the XAML used to configure one of the TextBlocksin AddingMachine<br />These settings position the control on the page and set up the text alignment<br />We need to add the numeric keyboard requirement<br />20<br />
    21. 21. XAML and attributes<br /><TextBox Height="72"HorizontalAlignment="Left" Margin="8,175,0,0" Name="secondNumberTextBox" Text="0"VerticalAlignment="Top" Width="460"TextAlignment="Center" /><br />The information about the TextBox is presently given as a series of attributes<br />You can think of an attribute as a simple name/value pair if you wish<br />These are given as part of a simple TextBox element<br />21<br />
    22. 22. Attributes and InputScope<br />The keyboard required for a TextBox is selected using the “InputScope” information for that TextBox<br />The InputScope is actually a collection of InputScopeName values <br />This makes it hard to express the InputScope as an attribute to the TextBox<br />So we have to change the format of the XAML used to describe the TextBox<br />22<br />
    23. 23. Configuring using attributes<br /><TextBox Height="72"HorizontalAlignment="Left" Margin="8,175,0,0" Name="secondNumberTextBox" Text="0"VerticalAlignment="Top" Width="460"TextAlignment="Center" <br />/><br />In this format the attributes are given between the <TextBoxand the /> delimiters<br />This is a great way to express simple items of configuration information<br />23<br />
    24. 24. Configuring using properties<br /><TextBox Height="72"HorizontalAlignment="Left" Margin="8,19,0,0" Name="firstNumberTextBox" Text="0"VerticalAlignment="Top" Width="460"TextAlignment="Center"><TextBox.InputScope><InputScope><InputScopeNameNameValue="Digits" /></InputScope></TextBox.InputScope></TextBox><br />This version of TextBox configuration uses a property list as well as attributes<br />24<br />
    25. 25. Attributes <br /><TextBox Height="72"HorizontalAlignment="Left" Margin="8,19,0,0" Name="firstNumberTextBox" Text="0"VerticalAlignment="Top" Width="460"TextAlignment="Center"><TextBox.InputScope><InputScope><InputScopeNameNameValue="Digits" /></InputScope></TextBox.InputScope></TextBox><br />The attributes are in the same place as before<br />But the TextBox now contains a list of properties<br />25<br />
    26. 26. Attribute delimiter <br /><TextBox Height="72"HorizontalAlignment="Left" Margin="8,19,0,0" Name="firstNumberTextBox" Text="0"VerticalAlignment="Top" Width="460"TextAlignment="Center"><TextBox.InputScope><InputScope><InputScopeNameNameValue="Digits" /></InputScope></TextBox.InputScope></TextBox><br />This character marks the end of the attributes for the TextBox<br />If there were no properties it would be /><br />26<br />
    27. 27. Properties<br /><TextBox Height="72"HorizontalAlignment="Left" Margin="8,19,0,0" Name="firstNumberTextBox" Text="0"VerticalAlignment="Top" Width="460"TextAlignment="Center"><TextBox.InputScope><InputScope><InputScopeNameNameValue="Digits" /></InputScope></TextBox.InputScope></TextBox><br />These are the properties for the TextBox<br />At the moment we just have the one, which is a list of InputScope items<br />27<br />
    28. 28. Property Delimiter<br /><TextBox Height="72"HorizontalAlignment="Left" Margin="8,19,0,0" Name="firstNumberTextBox" Text="0"VerticalAlignment="Top" Width="460"TextAlignment="Center"><TextBox.InputScope><InputScope><InputScopeNameNameValue="Digits" /></InputScope></TextBox.InputScope></TextBox><br />This marks the end of the properties for the TextBox<br />We could have lots of other properties<br />28<br />
    29. 29. Attributes in action<br /><Person name="Rob"/><br />As another example, consider a Person described in XAML<br />This person has a name attribute<br />We can express the attribute in the simple form above<br />This is a name/value pair<br />29<br />
    30. 30. Adding Properties<br /><Person name="Rob"> <AddressaddressType="HomeAddress"> <FirstLinetext="18 Pussycat Mews"/> <Towntext="Seldom"/> <Countytext="Wilts"/> <PostCodetext="NE1 410S"/> </Address></Person><br />Now the Person has both attributes and properties<br />The Address has attributes and properties too<br />30<br />
    31. 31. Attributes vs Properties<br />If you are holding a something simple and indivisible about an element, for example Height = 72, then an attribute makes very good sense<br />If you are holding something that is compound (i.e. contains sub elements), for example a list of InputScopeNames , then properties make good sense<br />31<br />
    32. 32. Properties<br /><TextBox Height="72"HorizontalAlignment="Left" Margin="8,19,0,0" Name="firstNumberTextBox" Text="0"VerticalAlignment="Top" Width="460"TextAlignment="Center"><TextBox.InputScope><InputScope><InputScopeNameNameValue="Digits" /></InputScope></TextBox.InputScope></TextBox><br />Since the input scope will contain a list of items it makes sense to use the Property format<br />32<br />
    33. 33. Attributes as Properties<br /><TextBoxHorizontalAlignment="Left" Margin="8,175,0,0" Name="secondNumberTextBox" Text="0"VerticalAlignment="Top" Width="460"TextAlignment="Center"> <TextBox.Height>72 </TextBox.Height></TextBox><br />We can actually express attributes as properties if we wish<br />The syntax is a bit long winded<br />33<br />
    34. 34. XAML wrap up<br />XAML “declares” the display elements and sets their attributes and properties<br />These are expressed in a customised form of XML<br />Attributes provide a simple way of giving setting information<br />Properties are more structured <br />They are equivalent, as they map onto properties of a .NET class<br />34<br />
    35. 35. Setting Properties in Code<br />// Make a new input scopeInputScopedigitScope = newInputScope();// Make a new input scope nameInputScopeName digits = newInputScopeName();// Set the new name to Digitsdigits.NameValue = InputScopeNameValue.Digits;// Add the name to the new scopedigitScope.Names.Add(digits);// Set the scope of the textbox to the new scopefirstNumberTextBox.InputScope = digitScope;<br />This is the C# to do the same thing…<br />35<br />
    36. 36. Demo 3: Setting InputScope<br />Demo<br />36<br />
    37. 37. Displaying a MessageBox<br />If you want to display a message box to alert the user of a situation, or ask for confirmation you can do this<br />The MessageBox class exposes a Show method that is used to display this<br />There are a number of options you can use to allow the user to confirm actions as well as acknowledge messages<br />37<br />
    38. 38. Simple Message<br />MessageBox.Show("Invalid Input" + System.Environment.NewLine + "Please re-enter");<br />You can create a multi-line message by breaking it with the Newline value<br />The Show method will not return until the user presses OK<br />38<br />
    39. 39. User Selection<br />if (MessageBox.Show("Do you really want to do this?","Scary Thing", MessageBoxButton.OKCancel) == MessageBoxResult.OK){// do scary thing here}else{ // do something else}<br />You can test the return value and use this to control program behaviour<br />39<br />
    40. 40. Using Assets in Windows Phone<br />We have seen that Visual Studio can use the project mechanism to allow you to combine code and assets such as images and sounds<br />These can then be used in your program to improve the user experience<br />Now we are going to find out how to manipulate these from within a program<br />40<br />
    41. 41. Adding an Asset<br />The plan is to use this image as the background to the AddingMachine program<br />It is a jpeg image that has been cropped from a larger picture<br />41<br />
    42. 42. Image Sizes<br />Remember that the Windows Phone is a slightly constrained device<br />Limited resolution screen (800x480)<br />Limited amount of program memory<br />Make sure when you add images that you don’t add them to a greater resolution than is required for the platform<br />Otherwise you will waste memory<br />42<br />
    43. 43. Adding an Asset<br />If we simply drag a file onto a project that file is added to the project<br />A copy of the file is made in the project directory and the project contains a link to this copy<br />43<br />
    44. 44. Linking to assets<br />You can use the Project>Add Existing Item dialog to add an asset<br />If you do this you can add the asset as a link rather than making a copy of it<br />This can be useful if you want several projects to share a single resource item<br />44<br />
    45. 45. Assets Build Action<br />When you add an asset to a project you specify how it is to be used in the solution<br />This is set as the “Build Action” of the asset<br />The two Build Actions we are going to consider are “Content” and “Resource”<br />45<br />
    46. 46. Assets as Content<br />An asset with the “BuildAction” of “Content” is copied into the folder alongside the program executable<br />The program can then open this file as it would any other<br />46<br />
    47. 47. The Image element<br /><Image Height="611"HorizontalAlignment="Left" Margin="8,0,0,0" Name="gearBackgroundImage" Stretch="Fill"VerticalAlignment="Top" Width="472" Source="AddingGears.jpg" /><br />Silverlight provides an Image element that will draw images on a page<br />The Image element has a source attribute that can identify a file of content to load the image from<br />47<br />
    48. 48. Silverlight Draw Order<br />Silverlight will draw elements in the order they are given in the XAML<br />If the image is drawn first it will have the other items drawn on top of it<br />48<br />
    49. 49. Demo 4: A background as Content <br />Demo<br />49<br />
    50. 50. Assets as Resources<br />An asset added as a Resource is stored as part of the program assembly file<br />The easiest way to add an image as a resource is to use the Visual Studio Toolbox to add an image<br />50<br />
    51. 51. The Source property of an Image<br />We can use the Source item in the Properties pane for an image to create a resource to load<br />If we click the browse button we can open a Choose Image dialog<br />51<br />
    52. 52. Image resources in the applicaiton<br />We are now looking for images held as resources in the application<br />At the moment there are not any<br />We can click Add to add an image as a resource<br />52<br />
    53. 53. Browsing for image resources<br />We can select one or more images to be added into the application as resources<br />We could add other file types as well<br />53<br />
    54. 54. An image resource<br />Once the image is added it has a particular path that can be used to locate it as a resource<br />This path will be added to the xaml for the Image element<br />54<br />
    55. 55. Using a resource in an Image<br /><Image Height="611"HorizontalAlignment="Left" Name="gearBackgrounds" Stretch="Fill"VerticalAlignment="Top" Width="472" Source="/AddingMachine;component/Images/AddingGears.jpg" /><br />This version of the source path locates the image as a resource in the assembly<br />When the Silverlight component is built it will now load the image from the assembly<br />55<br />
    56. 56. Demo 5: A background as a Resource<br />Demo<br />56<br />
    57. 57. Content vs Resources<br />Content<br />Smaller program<br />Faster load time for program, but slightly slower access to the resource<br />A bit more “untidy”<br />Resource<br />Larger program<br />Slower load time, but faster access to resources<br />Just a single file to deploy<br />57<br />
    58. 58. Review<br />Silverlight elements have many properties that can be manipulated by applications<br />Initialisation properties are best set in the xaml for an element<br />Elements are described by attributes and properties<br />A MessageBox is used to get a user response<br />Assets are added to an application as content (separate file) or resource (in assembly file)<br />58<br />
    59. 59. Data manipulation and display<br />
    60. 60. Topics<br />Responding to events from Silverlight elements<br />Using DataBinding to connect Silverlight elements to application classes<br />Adding classes as resources to a page<br />One way data binding<br />Two way data binding<br />
    61. 61. Silverlight element events<br /><Button Content="equals" Height="72"HorizontalAlignment="Left" Margin="158,275,0,0" Name="equalsButton"VerticalAlignment="Top" Width="160" Click="equalsButton_Click" /><br />privatevoidequalsButton_Click(objectsender, RoutedEventArgs e){calculateResult();}<br />We have seen how Silverlight elements can link to event handlers in the code for a page<br />61<br />
    62. 62. The TextChanged Event<br />A Button can generate Click events when it is clicked<br />A TextBox can generate TextChanged events if the user types in the TextBox<br />We can use this to create an AddingMachine that updates automatically<br />No need to press Calculate each time a new solution is required<br />62<br />
    63. 63. TextBox Events<br />The TextBox can generate lots of different events<br />We can create a binding to an event by double clicking the event in the Properties pane<br />This updates the xaml description of the control and adds an event handler<br />63<br />
    64. 64. Automatically calculating a result<br />privatevoidfirstNumberTextBox_TextChanged(objectsender,TextChangedEventArgse){calculateResult();}<br />Each time the text in the first number TextBox changes the calculation is performed<br />We can also bind an event to changes in the second TextBox too<br />64<br />
    65. 65. Double TextChanged Events<br />stringoldFirstNumber = "";privatevoidfirstNumberTextBox_TextChanged(objectsender, TextChangedEventArgse){if (firstNumberTextBox.Text == oldFirstNumber) return;oldFirstNumber = firstNumberTextBox.Text;calculateResult();}<br />There is a known issue with the TextChanged event. It may get fired twice<br />This code shows how to work round this<br />65<br />
    66. 66. Demo 1: Auto update AddingMachine<br />Demo<br />66<br />
    67. 67. Data Binding<br />This is a very important subject<br />It provides a coupling between the data in a program and the user interface<br />It removes the need to write “glue” logic to link program data to display elements<br />It can work in two ways<br />‘One-way’ <br />‘Two-way’<br />67<br />
    68. 68. One Way Data Binding<br />This creates a connection between a property in a display object and a property in a C# class<br />If the property in the class is changed, the property in the display element is changed too<br />We can use this in our AddingMachine to bind the result of the calculation to the display on the page<br />68<br />
    69. 69. Two Way Data Binding <br />This form of connection works in both directions<br />Changes to the display element fire events in the C# class <br />Changes to properties in the C# class cause the display element to update<br />We can use this in our AddingMachine to read numbers in from the user<br />69<br />
    70. 70. Creating an Adder class<br />The first thing we need to do is create a class that encapsulates the behaviour of the AddingMachine<br />This will expose the properties that we can bind to the display elements<br />Text in the top TextBox<br />Text in the bottom TextBox<br />Text in the result TextBlock<br />70<br />
    71. 71. Creating an object to bind to<br />publicclassAdderClass{privateinttopValue;publicintTopValue {get { returntopValue; }set { topValue = value; }}<br />// repeat for bottomValuepublicintAnswerValue {get { returntopValue + bottomValue;} }}<br />71<br />
    72. 72. The AdderClass<br />The AdderClass is the element in our program that will do all the business logic<br />We could give it to another programmer to fill in and they could put the behaviours behind the properties in the class<br />We could also create test versions to test the display<br />This is another example of separation of the program from the presentation<br />72<br />
    73. 73. Adding Notification Behaviour<br />publicinterfaceINotifyPropertyChanged<br />{<br />// Summary:<br />// Occurs when a property value changes.<br />eventPropertyChangedEventHandlerPropertyChanged;<br />}<br />For a class to be able to bind to display elements it must implement the INotifyPropertyChanged interface<br />This is how elements can register an interest in properties in the class<br />73<br />
    74. 74. Silverlight display elements<br />PropertyChanged(this,newPropertyChangedEventArgs("AnswerValue"));<br />When a Silverlight display element wants to be notified of a change to a property it will bind to the PropertyChanged event<br />The data object can then use the event to deliver a message that a property has changed<br />Above we are telling Silverlight the AnswerValue has changed<br />74<br />
    75. 75. Reading back the property<br />publicintAnswerValue{get {returntopValue + bottomValue; }}<br />When the Silverlight element reads the property it causes the result to be calculated and returned<br />This value will end up on the display<br />75<br />
    76. 76. Demo 2: AddingMachine with data binding<br />Demo<br />76<br />
    77. 77. Binding a class to the xaml<br />xmlns:local="clr-namespace:AddingMachine"<br />The C# business class must be bound to the xaml in a page so that the page can use it<br />We start by adding the namespace containing the class to the resources available to this page<br />A xaml file contains a list of the namespaces it is using<br />77<br />
    78. 78. Mapping a class to a resource<br /><phone:PhoneApplicationPage.Resources><local:AdderClass x:Key="AdderClass" /></phone:PhoneApplicationPage.Resources><br />The next step is to make a mapping between the AdderClass and the name we are using in the xaml page<br />In this case we are using the same name for both<br />You might want to use different classes or test classes in the xaml page<br />This lets you configure this in the xaml<br />78<br />
    79. 79. Adding the resource to an element<br /><Grid x:Name="LayoutRoot" Background="Transparent"DataContext="{StaticResourceAdderClass}"><br />The Grid control is the one that holds all the elements on our page<br />Adding a DataContext to a control makes it available to all the controls it contains<br />This means that our TextBlock and TextBox items can now all use that control<br />79<br />
    80. 80. Business Objects and Silverlight<br />We have now connected our AdderClass business object to Grid element and all the components in it<br />We only have to do this once for a class, no matter how many properties it contains<br />The next thing we need to do is bind the Silverlight element properties to the properties exposed by the AdderClass object<br />80<br />
    81. 81. Binding the top line to AdderClass<br />We are going to connect the Text in the first number textbox (the one in the top line) to the TopValue property in AdderClass<br />We do this from the Properties pane in Visual Studio<br />81<br />
    82. 82. Applying Data Binding<br />If we select “ApplyDataBinding” we are given a list of data sources and properties they expose<br />We select the one we want to use <br />Note that we have selected TwoWay binding<br />82<br />
    83. 83. One Way binding for the answer<br />When we bind the result text box this is only bound “OneWay”<br />There is no set method for this property in AdderClass<br />The program will only ever want to display results<br />The binding can only be OneWay<br />83<br />
    84. 84. Review<br />Silverlight elements can generate events that C# code can bind to<br />This includes changing text in a TextBox<br />Silverlight elements properties can also be bound to properties in C# business objects<br />The object implements an interface that exposes an event source that Silverlight can bind to<br />This can provide two way (input/output) or one way (output only) data binding<br />84<br />
    85. 85. Pages and navigation<br />
    86. 86. Topics<br />Creating multi-page applications<br />Navigating between pages<br />Using the Back button<br />Passing data between pages<br />Page navigation events<br />Sharing data in an application<br />
    87. 87. Multi-page applications<br />You often can’t fit all the required elements of an application on a single page<br />Alternatively you might want to have separate “options” or “settings” pages in your application<br />Silverlight on Windows Phone lets you add additional pages to an application and allow the user to navigate between them<br />Before you write the code you should “storyboard” the application and forms<br />87<br />
    88. 88. Adding another page<br />You add another page as you would any other item to a project<br />This creates the xaml and the C# code file<br />88<br />
    89. 89. Pages and projects<br />Pages that are added are stored in the same project as the main page<br />They will be compiled and transferred into the target device automatically<br />89<br />
    90. 90. Page Navigation<br />privatevoid page2Button_Click(object sender,RoutedEventArgs e){NavigationService.Navigate(newUri("/PageTwo.xaml",UriKind.RelativeOrAbsolute));}<br />The NavigationService object performs navigation for an application<br />Each Silverlight page has a Uri<br />The Navigate method takes the user to the specified page<br />90<br />
    91. 91. The UriKind<br />privatevoid page2Button_Click(object sender,RoutedEventArgs e){NavigationService.Navigate(newUri("/PageTwo.xaml",UriKind.RelativeOrAbsolute));}<br />The address of a resource can be expressed absolutely, or relative to the location the program is running from<br />RelativeOrAbsolute will work, but the navigation in this case is actually Relative<br />91<br />
    92. 92. Missing page exceptions<br />The uri to the destination page is a string of text<br />It is not a binding to a particular software object<br />If you spell the uri incorrectly the Silverlight will compile correctly and start running<br />The program will throw an exception if an incorrect uri is used to locate a page<br />92<br />
    93. 93. Using the Back button<br />The Back button is used on the Windows Phone to move backwards through the UI<br />This behaviour is built into Silverlight page navigation on the device<br />If the user presses Back they are automatically taken to the previous Silverlight page<br />If they press Back at the top level of the pages the program is ended<br />93<br />
    94. 94. Overriding the Back button<br />You often want to get control when a user tries to move off a page<br />You might want to confirm a save at that point<br />You can bind an event to the Back key pressed event which can do this<br />94<br />
    95. 95. Disabling the Back Button<br />privatevoidPhoneApplicationPage_BackKeyPress(object sender,System.ComponentModel.CancelEventArgse){e.Cancel = true;}<br />The event handler for the back button can cancel the back event<br />Binding the above method to the back button stops it from allowing navigation away from a page<br />95<br />
    96. 96. Using a MessageBox<br />privatevoidPhoneApplicationPage_BackKeyPress(object sender,System.ComponentModel.CancelEventArgse){if (MessageBox.Show("Do you really want to exit?","Page Exit", MessageBoxButton.OKCancel) != MessageBoxResult.OK) {e.Cancel = true; }}<br />This code adds a confirmation message<br />96<br />
    97. 97. Demo 1: Multi-page navigation<br />Demo<br />97<br />
    98. 98. Passing data between pages<br />Each Silverlight page is a separate entity<br />The code behind the page can hold data members but these are local to that page<br />You often want to pass data from one page into another<br />If the data is very simple you can just add it to the uri that is used to locate the page<br />98<br />
    99. 99. Assembling a data uri<br />privatevoid page3Button_Click(object sender,RoutedEventArgs e){NavigationService.Navigate(newUri("/PageThree.xaml?info=" + InfoTextBox.Text, UriKind.Relative));}<br />This event handler adds a data item onto the uri that is passed into the destination page<br />It reads text out of a textbox and appends that to the uri<br />The data is labelled as info<br />99<br />
    100. 100. Page navigated events<br />If the destination page is to use the data in the uri there must be a way of running some code when a page is navigated to<br />Silverlight provides methods to override in a page that give control when the page is navigated to and from<br />We are going to use the OnNavigatedTo event<br />100<br />
    101. 101. Loading data from the uri<br />protectedoverridevoid OnNavigatedTo (System.Windows.Navigation.NavigationEventArgs e){ string info = "";if (NavigationContext.QueryString.TryGetValue("info",out info) ) infoTextBlockFromQuery.Text= info;}<br />The NavigationContext object has a QueryStringproperty <br />TryGetValue will search for a value in the uri and return true if it has found the value<br />101<br />
    102. 102. Demo 2: Passing Data<br />Demo<br />102<br />
    103. 103. Sharing objects between pages<br />Each page in a program is a separate entity<br />It has its own member data, but is not able to refer to any other<br />When the program navigates to a page it does not provide a reference to the source page<br />To share data amongst pages we have to use the App.xaml object<br />103<br />
    104. 104. The App.xaml page<br />This is the ‘container’ for the whole application<br />It does not describe a page to be drawn, but it does hold methods that start the application running<br />It also contains some event handlers<br />104<br />
    105. 105. The App class<br />publicpartialclassApp : Application{// To be used from all pages in the applicationpublicstringLoginName;}<br />The App class for an application is an extension of the Application class provided by Silverlight<br />We can add our own members to this new class<br />Here I have added a string data member<br />105<br />
    106. 106. Getting a reference to the App<br />AppthisApp = App.CurrentasApp;LoginTextBox.Text = thisApp.LoginName;<br />The Current property of the Application class provides a reference to the currently active application<br />It is provided as a reference to an Application instance<br />We need to convert this into a reference to the App class that contains the data<br />106<br />
    107. 107. Demo 3: Shared Data<br />Demo<br />107<br />
    108. 108. Review<br />You can create multiple Silverlight pages and add them to your project<br />Navigation to pages is performed on the basis of uri (Uniform Resource Indicator) values<br />The back button normally navigates back to the source page, but this can be overridden<br />The uri can contain simple text messages<br />Pages can share larger objects in the App.xaml page <br />108<br />
    109. 109. Exercise 1: Adding error handling<br />
    110. 110. Exercise 2: Improvingtheuser interface<br />
    111. 111. Using data binding<br />

    ×