Archives For windows 8

Learn how to write code in Windows Store apps for Windows 8 that works with structured data in SQLite—a popular database that’s familiar to Android app developers.

Your app may need to work with data that’s more complex than simple key-value pairs—for example, a complex sales order or a survey with comments. For these kinds of data, you may want to use a database. One popular choice is SQLite—a self-contained, zero-configuration, relational, transactional database engine—which Android and Windows Store apps both support.

Here’s how to:

  • Install SQLite.
  • Reference it from a Windows Store app.
  • Get a helper library to make your coding easier.
  • Write code to create a database table.
  • Add, get, change, and remove the table’s records.

Installing SQLite

The first thing you’ll need to do is install the SQLite for Windows Store apps. This can be done by downloading the SQLite for Windows Runtime package

  1. In Visual Studio, click the Tools menu, then click Extensions and Updates

  2. In the tree on the left of the Extensions and Updates window, click Online, then click Visual Studio Gallery.
  3. Next, type sqlite in the search box in the upper right hand corner and press Enter.
  4. The SQLite for Windows Runtime package should appear. Click Download.

  5. You will then be prompted to click Install. Do so.

  6. Once the package is installed you will need to restart Visual Studio
Android tip
The SQLite for Windows Runtime package in Visual Studio is similar to the android.database.sqlite package.

Adding a Reference to SQLite

Now that SQLite is installed you need to add a reference to it from you project.

  1. Right click the References folder in your Windows Store project and click Add Reference…

  2. In the tree on the left hand side of the Reference Manager windows, expand the Windows and the Extensions nodes.
  3. Then select both the SQLite for Windows Runtime and the Microsoft Visual C++ Runtime Package and click OK.

  4. You should now see the extensions appear under the References folder for you project.

Visual Studio tip
After you add these references, your app’s project may not build or run. To fix this, on the Build menu, click Configuration Manager. In the Active solution platform box, click your specific target platform, such as ARM, x64, or x86. Then click Close.

Getting Helper Classes

The last thing you’ll want to do is obtain some helper classes that make working with SQLite a bit easier. There are a number available for Windows Store applications. The ones I prefer to use come from the sqlite-net library.

The sqlite-net library can be obtained from NuGet via the following steps

  1. Right click on the References folder in you Windows Store project and click Manage NuGet Packages…


  2. Expand the Online node in the left hand side of the Window.
  3. Enter sqlite in the search box in the upper right hand side of Window and press Enter.
  4. Select sqlite-net and click Install.


  5. Two source files will be added to your project: SQLite.cs and SQLiteAsync.cs.


  6. Build your project by pressing F6 to ensure it is set up correctly.
Visual Studio tip
NuGet is a Visual Studio extension that makes it easier to install and update third-party libraries and tools in Visual Studio. To learn more about NuGet, see the NuGet Gallery.After you get familiar with NuGet, you may find it easier to use the command-line version of NuGet. To get to it in Visual Studio, on the Tools menu, click Library Package Manager > Package Manager Console.

Using SQLite

In the last part of this section we’ll look at how to perform some basic tasks with SQLite in your Windows Store application.

Creating a Table

The first step you’ll need to take is to create a table that your application will use. For the sake of example, let’s say your application is storing blog posts in a SQLite table. Using the sqlite-net package you obtained in the last section, you can define the table by simply writing a class.

public class Post
{
 [PrimaryKey]
 public int Id { get; set; }
 public string Title { get; set; }
 public string Text { get; set; }
}

The PrimaryKey attributes come from the sqlite-net package. There are a number of attributes that the package provides that allow you to define the table’s schema.

Once the table is defined it needs to be created, which can be done like this:

private async void CreateTable()
{
    SQLiteAsyncConnection conn = new SQLiteAsyncConnection("blog");
    await conn.CreateTableAsync<Post>();
}

The “blog” parameter in the constructor for the SQLiteAsyncConnection class simply specifies the path to the SQLite database.

The Post type specified in the call to the CreateTableAsync method specifies the type of table that should be created. This maps back to the Post class created earlier.

Android tip
In Android apps, you create a table that extends the SQLiteOpenHelper class with code like this.

public void onCreate(SQLiteDatabase db) {    
 db.execSQL("CREATE TABLE Post ( Id INTEGER PRIMARY KEY, Title TEXT, Text TEXT )");
}

Inserting a Record

Now that the table is created, records can be added to it with the following code:

public async void InsertPost(Post post)
{
    SQLiteAsyncConnection conn = new SQLiteAsyncConnection("blog");
    await conn.InsertAsync(post);
}
Android tip
In Android apps, you can add a record with code like this.

public void insertPost(SQLiteDatabase db, String title, String text ) {    
 ContentValues values = new ContentValues();
 values.put("Title", title);
 values.put("Text", text);
 long newRowId;
 newRowId = db.insert("Post", null, values);
}

Retrieving Records

Retrieve a single records from the table with the following:

public async Task<Post> GetPost(int id)
{
    SQLiteAsyncConnection conn = new SQLiteAsyncConnection("blog");

    var query = conn.Table<Post>().Where(x => x.Id == id);
    var result = await query.ToListAsync();

    return result.FirstOrDefault();
}
Android tip
In Android apps, you could return a Cursor object containing a single record with code like this.

public Cursor getPost(SQLiteDatabase db, Integer id){    
 String[] projection = {"Id", "Title", "Text" };
 String selection = "Id LIKE ?";
 String[] selelectionArgs = { String.valueOf(id) };
 Cursor c = db.query( "Post", projection, selection, selectionArgs,  null, null, null);
 return c;
}

Retrieve all record from the table with the following:

public async Task<List<Post>> GetPosts()
{
    SQLiteAsyncConnection conn = new SQLiteAsyncConnection("blog");

    var query = conn.Table<Post>();
    var result = await query.ToListAsync();

    return result;
}
Android tip
In Android apps, you could return a Cursor object containing all records with code like this.

public Cursor getPosts(SQLiteDatabase db){    
 String[] projection = { "Id", "Title", "Text" }; 
 Cursor c = db.query( "Post", projection, null, null, null, null, null);
 return c;
}

Updating a Record

Updating a record requires the following code:

public async void UpdatePost(Post post)
{
    SQLiteAsyncConnection conn = new SQLiteAsyncConnection("blog");
    await conn.UpdateAsync(post);
}
Android tip
In Android apps, you can update a record with code like this.

public void updatePost(SQLiteDatabase db, Integer id, String title, String text ) {    
 ContentValues values = new ContentValues();
 values.put("Title", title);
 values.put("Text", text);
 String selection = "Id LIKE ?";
 String[] selelectionArgs = { String.valueOf(id) };
 int count = db.update("Post, values, selection, selectionArgs);
}

Deleting a Record

A record can be delete with the following:

public async void DeletePost(Post post)
{
    SQLiteAsyncConnection conn = new SQLiteAsyncConnection("blog");
    await conn.DeleteAsync(post);
}

Android tip
In Android apps, you can delete a record with code like this.

public void deletePost(SQLiteDatabase db, Integer id ) {    
 String selection = "Id LIKE ?";
 String[] selelectionArgs = { String.valueOf(id) };
 db.delete("Post", selection, selectionArgs);
}

Next Steps

To learn more about how to work with SQLite, see these resources.

Learn how to write code in Windows Store apps for Windows 8 to save files, like photos or documents. You can store these files in app-specific file locations or save them to external storage media, like a USB drive.

A user may want to save a document that they’re working on and immediately return to the saved document it when they return to some document editor app. Or a user may want to save the current photo from some photo editing app to a USB drive and then connect that USB drive to a TV or a digital picture frame to view later. You can help your users do this by saving the document to an app-specific location on the user’s device, and by saving the photo to external storage media.

Here’s how app-specific file storage works behind the scenes in Windows Store apps. Each app can store files to a separate set of directories (called the local, roaming, and temporary directories) on a particular device:

· The local directory contains files that exist only on the local device.

· The roaming directory contains files that exist on all devices where the user has installed the app.

· The temporary directory is like the local directory, but the system can remove its files at any time.

When a user installs a Windows Store app, Windows automatically creates these directories. You don’t need to worry about where to find them because Windows tracks them for you. You just use the ApplicationData class to access them. If the user ever uninstalls the app, Windows automatically removes the matching directories so you don’t even have to worry about cleaning them up.

Windows tip
If a user wants to store app-specific files that are particularly valuable or irreplaceable, have your app store them in a more permanent location instead, like the user’s SkyDrive.

To store files in external storage media, you can use the DeviceInformation and StorageDevice classes. More about that later.

Here’s how to do all of this in code.

Save a file to an app-specific directory

In a Windows Store app, to save a file named hello.txt, write code like this for the local directory.

var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("Hello.txt");
await FileIO.WriteTextAsync(file, "Hello world!");

Or write code like this for the roaming directory.

var file = await ApplicationData.Current.RoamingFolder.CreateFileAsync("Hello.txt");
await FileIO.WriteTextAsync(file, "Hello world!");

And you can write code like this for the temporary directory.

var tempFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("TempFile.txt");
Android tip
In Android apps, write code like this for the local directory.

String filename = "hello.txt";
String string = "Hello world!";
FileOutputStream outputStream;

outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());outputStream.close();

Set the file-creation mode to MODE_PRIVATE so that other apps can’t access your app’s files. Windows Store apps, in contrast, can access only their own files.

Write code like this for the temporary directory.

File tempFile;
tempFile = File.createTempFile("TempFile.txt", null, context.getCacheDir());

Saving a File to External Storage

In a Windows Store app you must declare the Removable Storage capability in the in the Package.appsxmanifest associated with your app

After you declare this capability, check to see if external storage media is available using code like this.

public async Task<bool> IsExternalStorageAvailable()
{
  var devices = await DeviceInformation.FindAllAsync(StorageDevice.GetDeviceSelector());
   if (devices.Count > 0)
    return true;
   else
    return false;
}

If the external storage media is available, create the file using code like this.

var storage = StorageDevice.FromId(deviceInformation.Id);
await storage.CreateFileAsync("HelloWorld.png");
Android tip
In Android apps, to do something similar, first request the WRITE_EXTERNAL_STORAGE permission in your app’s manifest, like this.

<manifest>
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>

After you request this permission, check to see if external storage media is available, using code like this.

public boolean isExternalStorageWritable() {    
 String state = Environment.getExternalStorageState();
 if (Environment.MEDIA_MOUNTED.equals(state)) {
   return true;
 }
  return false;
}

If the external storage media is available, you can then create the file. For example, to create a file in the media’s Pictures directory, write code like this.

File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "HelloWorld.png");

Next steps

To learn more about saving files, see these resources.

Users often want to save the highest level that they reached in a game and then continue playing at that level when they return to their game. Or they want to continue reading where they left off when they return to a book reader.

One way you can enable this is by saving key-value pairs that persist on the user’s device between sessions and even after an app closes. In Android apps, these key-value pairs are called shared preferences. In Windows Store apps, they’re called application settings or just app settings.

To read and write shared preferences in Android apps, you use the SharedPreferences class. To read and write app settings in Windows Store apps, you use the ApplicationData class.

Windows tip
In Windows Store apps, you can also create key-value pairs by using the Dictionary class, but such pairs are stored only in local memory. They go away after they go out of scope in your app’s code.

Here’s how app settings work behind the scenes for Windows Store apps. When a user installs an app, Windows creates a special location and some special registry entries on the device to store that app’s settings. You don’t need to worry about where to find this location and the registry entries, because Windows tracks them for you. You just use the ApplicationData class to access them. If the user ever uninstalls the app, Windows automatically removes the matching app settings location and registry entries. You don’t have to worry about cleaning them up.

Windows tip
You can store more than just app-related settings. For example, you can store documents that are related to that particular app. However, if the user uninstalls that app, those related documents will automatically be removed, too. If those documents are particularly valuable, store them in a more permanent location, like the user’s SkyDrive.An app’s related settings and files together are called its application data, or just app data. Only app settings are covered in this post.

In Windows Store apps, you can store app settings in two ways: local and roaming. Local settings are stored only on the current device. Roaming settings are shared among all devices that the user installed the app on.

Here are all of the data types that you can create app settings for.

Boolean Guid Rect UInt16
Byte Int16 Single UInt32
Char Int32 Size UInt64
Char16 Int64 String Uri
DateTime Object TimeSpan Void
Double Point UInt8

Here’s how to create and get app settings in code.

Create app settings

In a Windows Store app, to create a local app setting with a key of “Name” and a value of “Me”, write code like this.

var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
localSettings.Values["Name"] = "Me";

To create a similar roaming app setting, write code like this.

var roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;
roamingSettings.Values["Name"] = "Me";
Windows tip
While you can store app settings in both the local location and the roaming location, you don’t have to.
Android tip
In Android apps, to create a similar shared preference, write code like this.

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); 
SharedPreferences.Editor editor = sharedPref.edit(); 
editor.putString("Name", "Me"); 
editor.commit();

You can share preferences among apps by using interactive mechanisms in the ContentProvider, BroadcastReceiver, and Service classes. In contrast, Windows Store apps can access only their own app settings.

Get app settings

In a Windows Store app, to get a local app setting with a key of “Name” and a default value of “Me” (that is, the value “Me” is returned if the app can’t find the “Name” key), write code like this.

string nameValue = "";
var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;

Object value = localSettings.Values["Name"];

if (!value)
 nameValue = value.ToString();
else
 nameValue = "Me";

To get a similar, roaming app setting, write code like this.

string nameValue = "";
var roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;

Object value = roamingSettings.Values["Name"];

if (!value)
 nameValue = value.ToString();
else
 nameValue = "Me";
Android tip
In Android apps, to get a similar shared preference, write code like this.

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
string nameValue = sharedPref.getString("Name", "Me");

Next steps

To learn more about how to create and get app settings, see these resources:

· Quickstart: Local application data

· Quickstart: Roaming application data

· Application data sample

Over the past several weeks I’ve been posting about how to build your first Windows Store application if you’re an Android developer. I want to wrap this series by providing some useful links.

All Posts in this Series

  1. Setting up the Development Environment
  2. Creating Your First Windows Store Project
  3. Exploring the Windows Store Project
  4. Running the Windows Store Application
  5. Building a Simple User Interface
  6. Creating a Second Page
  7. Adding “Back” Navigation

If you would prefer a pdf of all seven posts you can get it here: http://aka.ms/AndroidToWindows8

Additional Windows 8 Development Resources

Over the past several weeks I’ve been working on some content I’m excited to finally share with you through a series of blog posts. This series will introduce you to Windows 8 development from an Android developer’s perspective. Through the course of the series you’ll create your first app. It won’t be anything pretty, but you’ll learn the ins and outs of the development environment, how to create a simple user interface, and how to perform navigation. Along the way you’ll see some Android Hints that will help make it easier for you to transition your existing skills to the Windows platform. You’ll also see some Visual Studio Tips to make you more productive in your development environment. Good luck!

As referred to in lesson four, there is no hardware “Back” button for Windows 8 devices. However, developers can add navigation to their apps using “Back” semantics. In this lesson you’ll learn how to navigate back to MainPage.xaml from SecondPage.xaml.

Start by opening MainPage.xaml and wrapping the <TextBlock> element in a vertical <StackPanel>. You should end up with something like this:


<StackPanel Orientation=”Vertical”>

<TextBlock x:Name=”messageFromUser” />


</StackPanel>

VISUAL STUDIO TIP

If you like your code to look “just so”, you can format it at any time by pressing Ctrl + K + D.

 

Now add a <Button> element under your <TextBlock> element, specifying the x:Name, Content, and Click attributes like so:

<StackPanel Orientation=”Vertical”>

<TextBlock x:Name=”messageFromUser” />


<Button x:Name=”goBack”


Content=”Go Back”


Click=”goBack_Click” />

</StackPanel>

Note: For the sake of this lesson a string resource was not added to Resources.resw for the message displayed in the <Button> element.

Open the code-behind file for SecondPage.xaml (press F7), and add the following method:


private
void goBack_Click(object sender, RoutedEventArgs e)

{


//Go back to MainPage.xaml if able to


if (this.Frame.CanGoBack)


this.Frame.GoBack();

}

ANDROID HINT

To perform similar navigation in Android you would enable “Up” in the action bar in your activity’s onCreate method:

 

@Override

public void onCreate(Bundle savedInstanceState) {


getActionBar().setDisplayHomeAsUpEnabled(true);


}

 

That’s all there is to it. Run your app (F5) and see what happens.

Congratulations! You just built your first Windows Store application. To learn more about building Windows Store apps, continue to follow this series. The next installment is Working with Data.

Previous Posts in this Series

  1. Setting up the Development Environment
  2. Creating Your First Windows Store Project
  3. Exploring the Windows Store Project
  4. Running the Windows Store Application
  5. Building a Simple User Interface
  6. Creating a Second Page

Additional Resources

I’m sure my wife will be the first to tell you this, but I am not a designer. Of course, I don’t pretend to be one either. However, there are times when I’m working on a Windows 8 or Windows Phone 8 app when I need a designer’s touch. Typically I’ll need a font, some imagery, an icon, or even a sound. Rather than spending hours working in Photoshop or Expression Design, I’ll go to a list of resources I’ve compile to find exactly what I’m looking for. Some charge, some don’t, and depending on what I need I’m more than willing to pay a fair price for the design asset I’m looking for. I thought I’d share my “go-to” design list for you in case you’re struggling to find what you need and you dread the thought of having to create something on your own

Fonts

Icons/Images

Sounds

Hope this helps!

Over the past several weeks I’ve been working on some content I’m excited to finally share with you through a series of blog posts. This series will introduce you to Windows 8 development from an Android developer’s perspective. Through the course of the series you’ll create your first app. It won’t be anything pretty, but you’ll learn the ins and outs of the development environment, how to create a simple user interface, and how to perform navigation. Along the way you’ll see some Android Hints that will help make it easier for you to transition your existing skills to the Windows platform. You’ll also see some Visual Studio Tips to make you more productive in your development environment. Good luck!

In the previous lesson you created a simple UI that accepts text from a user. In this lesson you’ll create a second page in your application to display the user’s input.

Create the Second Page

Right-click the project in Solution Explorer, click Add, and click New Item.

In the Add New Item dialog, select Windows Store under Visual C#.

Select the Blank Page template, give the page a name of SecondPage.xaml, and click Add.

You should now see SecondPage.xaml in Solution Explorer.

If SecondPage.xaml is not open, double-click it.

Add a <TextBlock> element to the <Grid> element. Be sure to specify its x:Name attribute;

<Grid Background=”{StaticResource ApplicationPageBackgroundThemeBrush}”>


<TextBlock x:Name=”messageFromUser” />

</Grid>

Respond to the Send Button

You now need to get the message from the first page to the second page. Start by opening up MaingPage.xaml.

To respond to the <Button> element’s Click attribute to the element

<StackPanel x:Name=”theStackPanel”

Orientation=”Vertical”>

<TextBlock x:Uid=”messageLabel” x:Name=”messageLabel” Text=”" />

<TextBox x:Name=”theMessage” />

<Button x:Uid=”sendButton” x:Name=”sendButton” Content=”"


Click=”sendButton_Click” />


</StackPanel>

ANDROID HINT

The Click attribute is similar to the android:onClick attribute of the Android <Button> element.

 

Open the code-behind file for MainPage.xaml (MainPage.xaml.cs) and add the following method:

private
void sendButton_Click(object sender, RoutedEventArgs e)

{

 

}

VISUAL STUDIO TIP

You can open a code-behind file for a file you’re working with in design view by pressing F7.

 

Now you need to do a couple of things. First you need to get the text the user entered, then you need to navigate to the second page. This can be accomplished by adding the following to the sendButton_Click method:

private void sendButton_Click(object sender, RoutedEventArgs e)

{


//Get the message from the <TextBox> element


var message = this.theMessage.Text;

 


//If the message is empty use a default


if (string.IsNullOrEmpty(message))

message = “Hello World!”;

 


//Navigate to SecondPage.xaml


this.Frame.Navigate(typeof(SecondPage), message);

}

ANDROID HINT

In Android you would create an Intent and call the startActivity method to navigate to the second page with code similar to the following:

 

public void sendButton_Click(View view) {

Intent intent = new Intent(this, SecondPageActivity.class);

startActivity(intent);

}

 

If you run your app now (F5) and press the button, you’ll notice that you go to the second page. We’ll work on displaying the message in the last part of this lesson.

Display the Message

Now that you’re able to navigate to SecondPage.xaml from MainPage.xaml you need to display the message the user entered.

Open SecondPage.xaml.cs (the code-behind file for SecondPage.xaml).

Locate the OnNavigatedTo method and add the following code:

protected override void OnNavigatedTo(NavigationEventArgs e)

{


//Get the message passed in from MainPage.xaml


var message = (string)e.Parameter;

 


//Display the message in the <TextBlock> element


this.messageFromUser.Text = message;


}

This simply retrieves the message from the first page and displays it on the second page.

Run the app (F5) to see the results!

Previous Posts in this Series

  1. Setting up the Development Environment
  2. Creating Your First Windows Store Project
  3. Exploring the Windows Store Project
  4. Running the Windows Store Application
  5. Building a Simple User Interface

Additional Resources

image

That’s right.  You read the headline correctly.  The iPhone Developers Meetup is working with Microsoft in an effort to give our members the greatest opportunity to get their applications into the most marketplaces. We are partnering with Microsoft to give you the tools and resources you need to get your iOS applications into the Windows Store.

If you don’t have time to read the entire post, remember this:

  1. Access to software and hardware, including a Microsoft Surface device and Windows Phone device to test your applications on
  2. Information on how to port iOS applications or start a new application from scratch
  3. Access to the Microsoft development experts and the Twin Cities’ Microsoft Technology Center developer labs

This program is a partnership between the Twin Cities’ iPhone Developers Meetup and Microsoft to provide resources so our members can port or create applications for the Windows Store or the Windows Phone Store.  Between now and June 30th, members will have access to the developer kit, Microsoft developer experts and programs, and the Microsoft Technology Center’s developer labs.

The developer kit contains a Microsoft Surface device, HTC 8x Windows Phone, Windows 8 Pro evaluation bits, and a USB drive with resources, install guides, etc. for running a Microsoft development environment on a Mac.  You can contact John Hibscher (john_hibscher at yahoo.com) to schedule use of the kit for up to five days at a time.  If our group can get 15 or more applications into the Windows Store by June 30th, we will be able to keep the kit and will raffle off the Microsoft Surface, the HTC 8x, and a copy of Windows 8 Pro to the members that get applications submitted and approved. 

The Microsoft Technology Center is one of the premier facilities for Microsoft development.  At the MTC, you will be able to schedule time in one of the Windows 8 developer labs where you can use PCs that are state-of-the-art for doing Windows development.  In addition, Microsoft development experts will be on hand to answer any of your questions while you are there.  The MTC developer labs are a great place to get an app started or push it that last mile to completion.

In addition to the resources that are in the kit, here are some additional links to help get you started.

If you have more questions, or want more info, you contact me via email (adgroc at microsoft.com), on Twitter (@codel8r) of find me at my weekly Office Hours (Adam’s Office Hours)

Thanks and good luck coding!

Earlier today I presented a session at Mobile March on Windows 8 for HTML and JavaScript developers. Rather than give you my slides, I thought I’d give you links to resources on the various features I discussed. This will allow you to quickly and easily dive into the features that interest you. Here you go:

Tools http://aka.ms/getvs12now
WinJS http://aka.ms/WinJS
Animations http://aka.ms/WinJSAnimations
Tiles and notifications http://aka.ms/WinJSTiles
Push notifications http://aka.ms/WinJSPush
Media capture http://aka.ms/WinJSMedia

Hope it helps!

Over the past several weeks I’ve been working on some content I’m excited to finally share with you through a series of blog posts. This series will introduce you to Windows 8 development from an Android developer’s perspective. Through the course of the series you’ll create your first app. It won’t be anything pretty, but you’ll learn the ins and outs of the development environment, how to create a simple user interface, and how to perform navigation. Along the way you’ll see some Android Hints that will help make it easier for you to transition your existing skills to the Windows platform. You’ll also see some Visual Studio Tips to make you more productive in your development environment. Good luck!

A Windows Store application is simply a collection of pages. A page is the interface seen by the end user.

ANDROID HINT

A page is similar to an Activity in Android development

 

Each page is designed for the end user to interact with the application. A page is composed of layout controls and various widgets. Only one page can be seen by the end user at a time.

ANDROID HINT

Unlike Android, there is no system level “Back” or application level “Up” button. However, developers can implement navigation within their application through “Back” or “Up” button semantics.

 

To better familiarize yourself with the user interface components of a Windows Store application the following table maps Android widgets to their Windows Store counterparts:

Purpose

Android

Windows Store

Display Text

TextView

TextBlock

Edit Text

EditText

TextBox

Radio Button

RadioButton

RadioButton

Check Box

CheckBox

CheckBox

Time Input

TimePicker

TimePicker

Date Input

DatePicker

DatePicker

Submit

Button

Button

Show Progress

ProgressBar

ProgressBar

Display a List of Components

LinearLayout

StackPanel

Vertical List of Components

ListView

ListView

2-Dimensionl Grid

GridView

Grid

Display an Image

ImageView

Image

 

This is by no means an extensive list. As with many development technologies there are a number of ways to perform the same task. For example, instead of using a ListView to display a vertical list in a Windows Store app I could simply use a StackPanel and set its orientation property accordingly. I could also using a ProgressRing instead of a ProgressBar in a Windows Store app to display changes in progress.

In this lesson you’ll learn how to create a simple interface for your Windows Store application.

Add a Text Field

For your UI you’ll want a label to tell the user what to do, a field where users can input text, and a button. You’ll start by adding the text field.

Open the MainPage.xaml file in the root directory of your project.

VISUAL STUDIO TIP

When you open a *.xaml file you’ll first see a split view. The top view contains a visual designer. This lets you build layouts using WYSIWYG tools. The bottom contains the markup generated by the designer. For this lesson, you’re going to work directly with the XAML. To give yourself more screenspace you can go to a “XAML only” view using the following steps.

  1. Click the button on the toolbar between the designer and the markup view. This will move the markup view to the top and designer view to the bottom.
  2. Click the button on the toolbar between the two views. This will minimize the designer.

 

Add a <StackPanel> element to the <Grid> element that was added to the page when it was created. Your markup should look like this:


<StackPanel x:Name=”theStackPanel”


Orientation=”Vertical”>


</StackPanel>

 

ANDROID HINT

A StackPanel is equivalent to a LinearLayout in Android development. It allows you to lay out child elements in either a verity or horizontal orientation.

 

The x:Name attribute is similar to the android:id attribute. However, you are not required to provide a x:Name attribute for your visual elements.

 

The Orientation attribute is identical to the android:Orientation attribute of the LinearLayout in Android. The default value for the Orientation attribute is Vertical.

 

Now add a <TextBox> element inside of the <StackPanel> element you just created. Be sure to provide a x:Name attribute for it. You should end up with something like this:

<StackPanel x:Name=”theStackPanel”

Orientation=”Vertical”>


<TextBox x:Name=”theMessage” />


</StackPanel>

Add String Resources

Next you’ll want to add a label to your page to instruct the user on what to do. You might be tempted to add a <TextBlock> element and sent its Text attribute to the text you want displayed. While this will work, it goes against best practices for localization. Before you add the label to the page, you need to add a resource file to your project to store the text you want to display in the UI.

ANDROID HINT

A resource (*.resw) file to store strings is similar to the res/values/strings.xml file used in Android projects.

 

To add a resource file, start by right-clicking the Project in Solution Explorer, click Add, then click New Folder. This will add a new directory to the project. Name the directory Strings.

Add a subdirectory to the Strings directory entitled en-US.

Right-click the en-US directory, click Add, and click New Item. This will open the Add New Item dialog.

VISUAL STUDIO TIP

You can also add a new item by pressing Ctrl + Shift + A on the keyboard.

 

In the tree on the left-hand side of the dialog under the Visual C# node, select General. Then select Resource File (.resw) from the options presented.

Leave the name of the file as Resources.resw and click Add.

You should now see the Resources.resw file under the en-US directory in Solution Explorer.

If the Resources.resw file is not already open double click it.

Add the message you want to display to the user to Resources.resw. You should end up with something that looks like this:

The name of the string resource is important. As you see in the image above it’s in two parts. The first part specifies the name of the visual element the resources will be used for (in this case messageLabel). The second part specifies the name of the property of the visual element you want to use the resource for (in this case the text property).

Add a Label

With the Resource file in place you’re now ready to add the label to your page.

Open MainPage.xaml if not’s not already open and add a <TextBlock> element above the <TextBox> element in the <StackPanel>. In order to leverage the appropriate string resource be sure to set the x:Uid element of the label to the corresponding to the resource name. You should end up with something like the following:

<StackPanel x:Name=”theStackPanel”

Orientation=”Vertical”>


<TextBlock x:Uid=”messageLabel” x:Name=”messageLabel” Text=”" />

<TextBox x:Name=”theMessage” />

</StackPanel>

Add a Button

The last thing you’ll need to do as part of this lesson is to add a <Button> element to the page so you can send the message the user enters to a second page.

Before you add the <Button> be sure to add a string resource for its Content property in the Resources.resw file.

Now add a <Button> element under the <TextBox> element in MainPage.xaml, being sure to specify the appropriate x:Uid attribute for localization.

<StackPanel x:Name=”theStackPanel”

Orientation=”Vertical”>

<TextBlock x:Uid=”messageLabel” x:Name=”messageLabel” Text=”" />

<TextBox x:Name=”theMessage” />


<Button x:Uid=”sendButton” x:Name=”sendButton” Content=”" />


</StackPanel>

Congratulations! You just created your first Windows Store UI. It might not be pretty, but it works. You can run your app now (press F5 or F6 to see the results).

Previous Posts in this Series

  1. Setting up the Development Environment
  2. Creating Your First Windows Store Project
  3. Exploring the Windows Store Project
  4. Running the Windows Store Application

Additional Resources