Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Phone_81_Development_for_Absolute_Beginners

.pdf
Скачиваний:
34
Добавлен:
10.02.2015
Размер:
18.77 Mб
Скачать

I’ll use the isViewing flag to branch the logic of what happens in each scenario:

I’ll clean up a little by removing an extraneous Frame.Navigate():

If we’re currently in the “view / delete” scenario, I’ll need to first delete the MapNote, then navigate back to MainPage.xaml. However, I have a problem … I currently have now way of getting to the MapNote that was loaded into the page. This will require I step back a bit and create a private reference to the MapNote…

Windows Phone 8.1 Development for Absolute Beginners – Page 350

… here I add a private field of type MapNote. Now, when in the “view / delete” scenario, I’ll use that instead of my locally scoped variable of the same name:

Therefore, I’ll remove the var keyword in front of the mapNote like so:

When someone clicks the delete button, I want a popup dialog to ask the user if they’re sure they want to delete the MapNote. This will prevent an accidental deletion. To accomplish this, I add code to display a MessageDialog object. The MessageDialog will have two

Commands (rendered as buttons) … “Delete” and “Cancel”. Regardless of which one the user clicks, both will trigger the execution of a handler method called “CommandInvokedHandler”.

Finally, there are two lines of code that are unnecessary in this instance, but useful when creating a Windows Store app: I set the default command that should be executed when the user clicks the Esc key on their keyboard. Again, not pertinent here, but it won’t hurt and you

Windows Phone 8.1 Development for Absolute Beginners – Page 351

can see how to implement that. Finally, once we’ve properly set up the MessageDialog we call

ShowAsync() to display it to the user:

Of course, I’ll have to resolve namespaces by adding some using statements:

Next, I’ll implement the CommandInvokedHandler(). I’ll use the Label property of the command button that was clicked to determine which action to take, whether Cancel or Delete.

I’m only interested in the Delete scenario. I’ll call DeleteMapNote() then Frame.Navigate():

Windows Phone 8.1 Development for Absolute Beginners – Page 352

I’ll need to clean up those two lines of code in the addbutton_Click() event handler method since I don’t need them any more. In the screenshot below, I removed them both from the “view / delete” scenario:

Also, to resolve all of the compilation errors, I’ll need to add the async keyword since I’m calling a method that can be awaited:

When I’m finished, this should be the result … the entire code listing for

AddMapNote.xaml.cs:

using MapNotes.DataModel;

Windows Phone 8.1 Development for Absolute Beginners – Page 353

using System;

using System.Collections.Generic; using System.IO;

using System.Linq;

using System.Runtime.InteropServices.WindowsRuntime; using Windows.Devices.Geolocation;

using Windows.Foundation;

using Windows.Foundation.Collections; using Windows.UI.Popups;

using Windows.UI.Xaml;

using Windows.UI.Xaml.Controls;

using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data;

using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation;

namespace MapNotes

{

public sealed partial class AddMapNote : Page

{

private bool isViewing = false; private MapNote mapNote;

public AddMapNote()

{

this.InitializeComponent();

}

protected async override void OnNavigatedTo(NavigationEventArgs e)

{

Geopoint myPoint;

if (e.Parameter == null)

{

// Add isViewing = false;

var locator = new Geolocator(); locator.DesiredAccuracyInMeters = 50;

// MUST ENABLE THE LOCATION CAPABILITY!!!

var position = await locator.GetGeopositionAsync(); myPoint = position.Coordinate.Point;

Windows Phone 8.1 Development for Absolute Beginners – Page 354

}

else

{

// View or Delete isViewing = true;

mapNote = (MapNote)e.Parameter; titleTextBox.Text = mapNote.Title; noteTextBox.Text = mapNote.Note; addButton.Content = "Delete";

var myPosition = new Windows.Devices.Geolocation.BasicGeoposition(); myPosition.Latitude = mapNote.Latitude;

myPosition.Longitude = mapNote.Longitude;

myPoint = new Geopoint(myPosition);

}

await MyMap.TrySetViewAsync(myPoint, 16D);

}

private async void addButton_Click(object sender, RoutedEventArgs e)

{

if (isViewing)

{

// Delete

var messageDialog = new Windows.UI.Popups.MessageDialog("Are you sure?");

//Add commands and set their callbacks; both buttons use the same callback function instead of inline event handlers

messageDialog.Commands.Add(new UICommand( "Delete",

new UICommandInvokedHandler(this.CommandInvokedHandler))); messageDialog.Commands.Add(new UICommand(

"Cancel",

new UICommandInvokedHandler(this.CommandInvokedHandler)));

//Set the command that will be invoked by default messageDialog.DefaultCommandIndex = 0;

//Set the command to be invoked when escape is pressed messageDialog.CancelCommandIndex = 1;

//Show the message dialog

Windows Phone 8.1 Development for Absolute Beginners – Page 355

await messageDialog.ShowAsync();

}

else

{

// Add

MapNote newMapNote = new MapNote(); newMapNote.Title = titleTextBox.Text; newMapNote.Note = noteTextBox.Text; newMapNote.Created = DateTime.Now; newMapNote.Latitude = MyMap.Center.Position.Latitude;

newMapNote.Longitude = MyMap.Center.Position.Longitude; App.DataModel.AddMapNote(newMapNote); Frame.Navigate(typeof(MainPage));

}

}

private void cancelButton_Click(object sender, RoutedEventArgs e)

{

Frame.Navigate(typeof(MainPage));

}

private void CommandInvokedHandler(IUICommand command)

{

if (command.Label == "Delete")

{

App.DataModel.DeleteMapNote(mapNote); Frame.Navigate(typeof(MainPage));

}

}

}

}

The app should work as I test all the scenarios of adding, viewing and deleting a

MapNote as I move the Emulator’s location around the world.

The final change I want to make is to account for the possibility that a given note has a very long title. Currently, the letters will disappear off the right-hand side or possibly wrap to the next line (unless you set the height of the TextBlock):

Windows Phone 8.1 Development for Absolute Beginners – Page 356

At the very least, I can add a few properties to prevent both wrapping AND trim the final letters that will appear off screen using the TextWrapping and TextTrimming properties, respectively:

I’ll also add the TextWrapping property to the Note TextBlock:

Now, my MapNotes will appear correctly on screen:

Another successful Exercise. Hopefully this exercise was helpful in cementing many of the ideas we’ve already covered. At a minimum, you saw how we were able to reuse a lot of the

Windows Phone 8.1 Development for Absolute Beginners – Page 357

DataSource / Data Model code. If your data model is flat (i.e., not a deep hierarchy of relationships between classes), you now have a good recipe / template that you can re-use. It allows you to store your object graph to the Phone’s storage and grab it back out. All you have to do is create a new class that can be serialized. Even if you have Commands defined you can add the IgnoreDataMemberAttribute to those members that you do not want to be serialized.

We also looked at how to utilize the Map Control, how to change its Geoposition using the Geolocator and how to create an instance of a Geopoint using a latitude, longitude, how to display a MessageDialog and handle the callback function and much more.

Windows Phone 8.1 Development for Absolute Beginners – Page 358

Lesson 30: Series Conclusion

Let me congratulate you on making it all the way through this series. Think about how far you’ve come in such a short amount of time! It takes a high degree of commitment to work your way through 10 hours of content, but you did it, and you definitely have what it takes to see a project through to the end. And so, I’m confident that you can build the next great app. I would encourage you to take your time, aim high, and test, test, test your app to make sure your app is polished and ready for others to use it.

I love to hear from people who have watched these series I’ve created and who have built an app and submitted it to the app store. That’s probably the best feedback that we can get … that this series helped you in some small way and that you actually built an app and released it into the Windows Store. If that describes you, and if you need a beta tester, by all means please send me a tweet @bobtabor or write me at bob@learnvisualstudio.net.

Before I wrap this up, I want to thank Larry Lieberman and Matthias Shapiro who sponsored this series. If you like this content, please let them know … there’s a feedback link on the footer, or just leave a comment below this video.

Also, I want to thank Channel9 for their ongoing support of my work, including Golnaz Alibeigi, and those I’ve worked with in the past who have taught me so much, like Clint Rutkas who got a major promotion to the Halo team and of course, Dan Fernandez who I’ve been working with for over 10 years and who has keep me connected with Microsoft. It is much appreciated.

Allow me to make one last plug for my website, www.LearnVisualStudio.NET. I try to share everything I know with my clients about C#, Visual Studio, Windows and web development, data access, architecture and more.

Finally, I honestly wish you the best in your career and in life. Thank you.

Windows Phone 8.1 Development for Absolute Beginners – Page 359

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]