CHAPTER 10

image

The Windows User Interface

With the inception of Windows 8, Microsoft made it possible for developers to create and publish applications, known as Windows Store apps, which could be installed on desktops, laptops, or tablets running Windows 8. Similar to Windows Phone apps, developers could easily publish their applications to make them available across a wide global audience. However, only a small subset of APIs were reusable across the Windows Store and Windows Phone applications, which quickly became a major sticking point among developers who were attempting to target Windows systems and Windows Phone devices.

The announcement of Windows 8.1 at the Microsoft Build conference in April 2014 provided quite a bit of excitement among .NET developers because it introduced a converged API between Windows Store and Windows Phone Store applications. The reality of being able to share a larger portion of code logic, including XAML and UI assets, brought developers another step closer to the potential of targeting multiple platforms with a single codebase. Well, almost. Multiple platforms simply meant being able to target tablets, PCs, and devices running Windows. Baby steps, right?

As we touched on in Chapter 9, Microsoft has announced that the dream of developing one application to target multiple Windows platforms will be a reality with the release of Windows 10 in late July 2015. The concepts that we discussed throughout this book surrounding the XAML user interface design will still apply when you make the move to Windows 10 development.

That being said, much of the content we covered in Chapter 8 and Chapter 9 also apply to designing the Windows Store user interface, so we won’t rehash what we’ve already discussed. If you skipped over those chapters in haste, take a step back and read them before moving on in this chapter to ensure that you have a solid foundation for the advanced topics that we will be covering here.

The Basics

Before digging into Windows Store development, we will need to cover the pertinent information regarding the Windows SDK, developer licensing, and the basic design principles surrounding the Windows Store user interface.

Windows Software Development Kit

To develop Windows Store applications, the Windows SDK for Windows 8.1 must be installed on the development machine. It contains all of the necessary APIs and tools, including the Windows App Certification Kit, which is used to test apps for certification in the Windows Store. The good news here is that there is nothing additional that you will need to do to obtain the SDK since it is automatically installed with Visual Studio 2013 Update 2 or newer.

Developer License

Before you can create a Windows Store app in Visual Studio, you must install a developer license on your development machine. The license enables you to test your Windows Store applications prior to certification and publication in the store. When you attempt to create a new Windows Store app or open an existing Windows Store app using Visual Studio 2013, you will be prompted to obtain a developer license, as shown in Figure 10-1.

9781430267768_Fig10-01.jpg

Figure 10-1. Prompt to install developer license for Windows 8.1

Review the terms of the license. If you want to proceed, then click the I Agree button. You will then be prompted with the User Account Control dialog, as shown in Figure 10-2.

9781430267768_Fig10-02.jpg

Figure 10-2. Click Yes in User Account Control dialog to install the license

Click the Yes button to continue with the installation. Once the license is installed on your machine, it is valid for a period of one year. When the license has reached its expiration date, you will be prompted to install a new license at that time.

Basic Design Principles

Windows Store apps follow a clean, modern design practice, incorporating some of the distinctive features available in the Windows 8.1 operating system. To design Windows Store applications effectively, it is important to understand the key elements that make store applications so unique.

When launched, Windows Store applications run full-screen, as illustrated in Figure 10-3.

9781430267768_Fig10-03.jpg

Figure 10-3. Adobe Reader Windows Store app

Users can drag a running Windows Store application to the left or right of the screen to force the app to snap to the respective side within a pane. This allows the user to interact with multiple Windows Store applications at the same time, as shown in Figure 10-4.

9781430267768_Fig10-04.jpg

Figure 10-4. Windows Store apps may be snapped to the left or right side of the screen

As you can see, Adobe Reader has been snapped to the right side of the screen so that the user can also interact with Internet Explorer. Notice how the Adobe Reader’s layout automatically reflowed to adapt to the size of the pane. This is an important part of designing Windows Store applications. You must ensure that your application will be able to adapt to these types of changes. We will discuss this more in the next section, “Managing Layouts.”

Another important design element to consider is the Application Bar. As we mentioned in Chapter 9, the markup to include an Application Bar within Windows Phone applications is the same markup that you will use for Windows Store applications. While Windows Phone applications could display only a single Application Bar at the bottom of the page, Windows Store applications have the option to display up to two Application Bars on a single page—one at the top of the page and the other at the bottom. An Application Bar will be displayed at the top of the page if placed within the Page.TopAppBar element. Alternatively, an Application Bar will be displayed at the bottom of the page if placed within the Page.BottomAppBar element. The Application Bars will appear when the user swipes from the bottom edge of the screen downward or when the user right-clicks. Figure 10-5 illustrates an example of making use of both the top and bottom Application Bars in a Windows Store app.

9781430267768_Fig10-05.jpg

Figure 10-5. The primary and secondary Application Bars available within a Windows Store app

Since we have already discussed the details and implementation of the Application Bar in Chapter 9, we won’t cover it here since the same information applies to using it within your Windows Store applications.

Windows 8.1 provides a set of Charms that enable applications to integrate with core features within the operating system, such as Search, Settings, and Share. The Charms bar can be brought into view when swiping from the right edge inward, hovering the mouse pointer in the top or bottom right corner, or pressing the Windows+C shortcut key combination. Figure 10-6 shows the Charms bar.

9781430267768_Fig10-06.jpg

Figure 10-6. The Charms bar appears on the right side of the screen

In addition, Windows Store apps may make use of flyouts to collect information from the user, show more details about an item, or ask the user to confirm an action. Figure 10-7 depicts a couple of examples for using flyouts in your application. We will discuss this feature in detail in the “Flyouts” section later in this chapter.

9781430267768_Fig10-07.jpg

Figure 10-7. Flyouts can be used to provide pop-up menu options or display a message prompt

Gestures

Windows Store apps should all be designed for touch. This is easy to do so since all UI controls will respond to the following, which are common gestures recognized by the operating system.

  • Tap: Tapping invokes the primary action on the element that receives the tap (for example, tapping a button).
  • Press and hold: Pressing and holding displays detailed information about the selected element (for instance, displaying a tooltip).
  • Slide to pan: Swiping left or right will pan across the page (for example, Hub control behavior).
  • Cross slide to select: Sliding a short distance, perpendicular to the panning direction, will select an item (for instance, selecting an item in the list).
  • Cross slide to move: You can drag and drop a control across the page.
  • Pinch and stretch to zoom: You can drag fingers close together to pinch or drag fingers apart to stretch. These gestures are used to resize an element or to switch between the views in the SemanticZoom control.
  • Rotate: You can select an item and turn to rotate the selected item.
  • Swipe from edge: Depending on the location from which the swipe starts and the direction that the swipe takes, a specific action is performed.
    • Swiping from the right edge displays the Charms bar.
    • Swiping from the bottom edge displays the Application Bar.
    • Swiping from the left edge displays running apps.
    • Swiping from the top edge to the right/left splits the window.
    • Swiping from the top edge down to the bottom edge closes the app.

Managing Layouts

Windows Store apps may be run on devices of varying sizes—from 10" tablets to desktop systems leveraging full-size monitors, as well device orientation. Tablets may be run in portrait or landscape mode, so it’s natural to consider which orientation your application will support.

In addition to screen size and orientation, applications must also consider the available screen real estate. As mentioned earlier in this chapter, Windows Store applications may run full-screen or be snapped in a pane that can be resized to various widths. The minimum width for which you must design depends on the supported minimum width set within the application’s manifest file, Package.appxmanifest, as shown in Figure 10-8.

9781430267768_Fig10-08.jpg

Figure 10-8. Configuring the minimum width supported by the application in the application manifest

By default, the minimum supported width will be 500px. If you want to support a width of 320px, simply select that option within the “Minimum width” field in the manifest.

The application’s height will always occupy the full height of the screen. Only the application width real estate will vary since multiple apps can be run side-by-side and the user will have the ability to resize panes dynamically. Your application must continue to render properly despite the screen size that it is afforded by the user.

When designing your Windows Store application, you must determine how your application will look as its available width expands or contracts. As we mentioned in Chapter 8 and Chapter 9, avoid using fixed sizes in your XAML views. Allow the XAML subsystem to adjust automatically to the screen size that your application is afforded by the user.

Visual States

There will be cases when you will want to ensure that your page renders in a different format when the application window is snapped or resized. You can accomplish this by defining the visual states that your page will support using the VisualState class from the Windows.UI.Xaml namespace. The VisualState class enables you to configure the appearance of a control when it is in a specific state. However, to manage a collection of visual states as well as the logic for transitions between controls, you must make use of the VisualStateManager. Within XAML, you will define one or more visual states using the VisualStateManager.VisualStateGroups collection, as shown in Listing 10-1.

In the example in Listing 10-1, we have defined three visual states: Snapped, Narrow, and Default. Don’t get too hung up on the names since you can name the visual states using whatever convention makes sense to you. The names you provide here will be referenced in the code-behind, which we will get to shortly.

Storyboards and Animations

Once you have decided the various widths that you want to support, you must determine how your page will appear in each of those views. For example, if a StackPanel is rendering controls horizontally while the application window is in full view, you may want to change it to render controls vertically when the application is snapped to the left or right edge of the screen. Changing the way the control is rendered can be thought of as a visual transition. Visual transitions can be used to change any Windows Runtime dependency property on a control.

In XAML, you will be able to define the visual transitions that you want to be applied to a control as it moves from one visual state to another. This is accomplished through the use of storyboards and animations. Animations add movement within your application, providing appealing transitions as property values on a control are changed. Storyboards control the animations that are run using a timeline.

You can create animations for Color, Double, Point, and Object properties using the animations listed in Table 10-1.

Table 10-1. Windows Runtime Animations

Animation

Animates the Value of...

ColorAnimation

A Color property between two target values over a specified Duration

ColorAnimationUsingKeyFrames

A Color property along a set of keyframes

DoubleAnimation

A Double property between two target values over a specified Duration

DoubleAnimationUsingKeyFrames

A Double property along a set of keyframes

ObjectAnimationUsingKeyFrames

An Object property along a set of keyframes over a specified Duration

PointAnimation

A Point property between two target values over a specified Duration

PointAnimationUsingKeyFrames

A Point property along a set of keyframes

Using the example mentioned earlier, Listing 10-2 demonstrates how to change the StackPanel orientation when the window is snapped.

Listing 10-2 demonstrates the use of the ObjectAnimationUsingKeyFrames class to transition the StackPanel from horizontal to vertical orientation by defining the StackPanel’s new orientation property within the DiscreteObjectKeyFrame.Value element.

<DiscreteObjectKeyFrame KeyTime="0">
    <DiscreteObjectKeyFrame.Value>
         <Orientation>Vertical</Orientation>
</DiscreteObjectKeyFrame>

The number of animations that you want to include within a single storyboard is not limited. You can change as many property values as you need there. For example, if you also wanted reduce the text size of the Title text block when the window is snapped, you could include an additional animation in the storyboard definition for the Snapped visual state as follows:

<DoubleAnimation Duration="0"
                 To="21"
                 Storyboard.TargetProperty="FontSize"
                 Storyboard.TargetName="TitleTextBlock" />

Note that, in this case, the FontSize is changed through the To property on the DoubleAnimation element.

When configuring an animation for a specific control, you must specify the target control’s name and the property to which the animation must be applied. You can accomplish this by setting the attached properties TargetName and TargetProperty on the animation: <ObjectAnimationUsingKeyFrames Storyboard.TargetName="MyStackPanel" Storyboard.TargetProperty="Orientation">.

Notice that when the TargetName has been configured, the TargetProperty will automatically populate its selection list with only those properties that are applicable to the target UI element, enabling you to have complete control over the appearance of any object within the page.

You must also specify a Duration or KeyTime to indicate how long the animation will take to complete. When defining a duration for a visual state transition, use zero-duration animations to ensure that the application remains responsive. Setting a longer duration may negatively affect performance on the UI thread and lock up the application until the animation completes.

OnSizeChanged

Now that you know how you can define a view for each of the visual states that your application will support, how does the VisualStateManager know how to render the page?

To ensure the appropriate visual state is rendered when the application window’s width is resized, you must register for the Page’s OnSizeChanged event. The OnSizeChanged event receives the SizeChangedEventArgs parameter, which exposes two Size properties: NewSize and PreviousSize. You can use these properties to retrieve the Height and Width of the application window before and after it was resized.

Within the OnSizeChanged event, you will need to call the VisualStateManager.GoToState method, passing in the desired visual state to render. In this case, you will use the e.NewSize.Width property to determine which visual state to render. You must decide the maximum width that each visual state will support. Will a width of 500px or less trigger your Snapped view, or will it be 320px? What will the next maximum supported width be after that? These are design considerations that you must define based on your application. Listing 10-3 demonstrates an example of how to trigger the appropriate visual state based on the window’s new width size.

Taking the time to configure visual states within your application will ensure that your users have a seamless experience regardless of the screen real estate that is available to your app at runtime. Although it does require some legwork up front, the end result will be a polished, high-quality application that will be appealing to your users.

Searching Data

One of the fundamental features that all data-driven applications should provide is a mechanism to allow users to search and filter through data to find a particular item or group of items.

The Windows 8.1 SDK includes a SearchBox control to enable you to include advanced search capabilities within your application. Although the SearchBox itself is a simple control with no real functionality driving it, the control includes integration points, which you can leverage to incorporate search using your own custom logic. It includes additional features that make it easy to display a polished search interface, such as displaying suggestions based on the user’s current entry, as shown in Figure 10-9.

9781430267768_Fig10-09.jpg

Figure 10-9. SearchBox with a list of suggestions displayed based on the user’s search criteria

You may subscribe to one or more of the following events to add functionality to the SearchBox:

  • SuggestionRequested: Handle this event to provide new suggestions in the search pane based on the user’s search text.
  • QueryChanged: Handle this event to take action as the user types in the SearchBox. This may affect performance, so use with caution.
  • QuerySubmitted: Handle this event to control the action that is triggered when the user submits a search query.
  • ResultSuggestionChosen: Handle this event to control the action that is triggered when the user selects a suggested search result.

To include a SearchBox within a Windows Store page, simply include the element’s markup, <SearchBox />, along with any properties or events that you want to set. Here’s an example:

<SearchBox x:Name="CompanySearchBox"
        MinWidth="200"
        HorizontalAlignment="Right"
        QuerySubmitted="SearchBoxOnQuerySubmitted"
        SuggestionsRequested="SearchBoxOnSuggestionsRequested" />

As mentioned earlier, the SearchBox will display a list of suggestions, or a search history list, when the page is rendered. To turn off the list display, simply set its Boolean property, SearchHistoryEnabled, to False.

When the SearchHistoryEnabled property is set to True, the list will display up to 20 items in total. The first five items will be displayed in the pop-up, while the remaining items in the list may be scrolled into view.

To set the search history list to populate forcibly or to clear it, you can instantiate a SearchSuggestionManager object. This object provides an AddHistory method to allow you to add strings to the search history list. In turn, it also provides a ClearHistory method to enable you to clear the search history list.

If you want to display a Search Results page when the user submits the query entry by hitting Enter, you can easily incorporate this into your application by adding the Search Results Page template, as shown in Figure 10-10.

9781430267768_Fig10-10.jpg

Figure 10-10. Adding a search results page to the application

The Search Results Page template provides the UI layout and most of the code needed to render a polished results list. With a few minor tweaks, you will have a fully functional results page with little effort. You can create your own custom results page, if you so choose. This just provides a quick and easy alternative.

In the Search Results page code-behind, within the navigationHelper_LoadState event, add an entry to the DefaultViewModel dictionary for the Results collection. You will need to code your own custom search logic within your ViewModel to retrieve the results based on the query text entered. For example, in the case where you are searching only on company names, your ViewModel may expose a simple method to retrieve all companies that contain the query text entered as follows:

public ObservableCollection<Company> GetSearchResults(string queryText)
{
    return new ObservableCollection<Company>(Companies
            .Where(c => c.CompanyName.Contains(queryText))
            .ToList<Company>());
}

Within the search results code-behind file, you would simply add a line of code to include the results of this call to the DefaultViewModel["Results"] entry, as shown here:

private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
    var queryText = e.NavigationParameter as String;

    ...

    //Add your custom results to the DefaultViewModel
    this.DefaultViewModel["Results"] = App.MainViewModel.GetSearchResults(queryText);
}

The XAML within the search results page needs to be modified slightly to ensure the bound properties within the resultsGridView match the items exposed on the model on which you will be searching. In this example, you are searching on a collection of Company objects. Therefore, each result will depict a Company object. You modify the XAML in the resultsGridView to reference the properties within your Company object: LogoImagePath, CompanyName, Headquarters, and YearFounded.

<GridView x:Name="resultsGridView"
         ...
         ItemsSource="{Binding Source={StaticResource resultsViewSource}}">
         <GridView.ItemTemplate>
             <DataTemplate>
                 <Grid Width="294" Margin="6">
                     <Grid.ColumnDefinitions>
                          <ColumnDefinition Width="Auto" />
                          <ColumnDefinition Width="*" />
                     </Grid.ColumnDefinitions>
                     <Border ...>
                         <Image Source="{Binding LogoImagePath}"
                                Stretch="UniformToFill" />
                     </Border>
                     <StackPanel Grid.Column="1"
                                 Margin="10,-10,0,0">
                          <TextBlock Text="{Binding CompanyName}"
                                     TextWrapping="NoWrap"
                                     Style="{StaticResource BodyTextBlockStyle}" />
                          <TextBlock Text="{Binding Headquarters}"
                                     TextWrapping="NoWrap"
                                     Style="{StaticResource BodyTextBlockStyle}" />
                          <TextBlock Text="{Binding YearFounded}"
                                     TextWrapping="NoWrap"
                                     Style="{StaticResource BodyTextBlockStyle}" />
                        </StackPanel>
                 </Grid>
            </DataTemplate>
       </GridView.ItemTemplate>
        ...
  </GridView>

Finally, you need to modify the MainPage code-behind to add functionality to the SearchBox. In this example, you ensure that the following actions are handled with respect to the SearchBox:

  • Display the search history list only when the control has focus.
  • Add suggestions to the search history list when the onsuggestionsrequested event is raised.
  • Clear the search history list each time the page is loaded or when the list will be populated with a new list of suggestions.
  • Navigate to the search results page when the querysubmitted event is raised.

Note that this is a simple example of how to include SearchBox functionality. You have the flexibility to add logic that makes sense within the context of your application. Listing 10-4 shows the resulting code from the example.

If configured properly, upon typing text into the SearchBox and hitting the Enter key on the MainPage, the search results page should appear with a similar layout as the one that is depicted in Figure 10-11.

9781430267768_Fig10-11.jpg

Figure 10-11. Search results page displaying list of matching items

As you can see, the Search Results Page template provides you with a great starting point. However, we highly recommend that you leverage the knowledge you have gained so far to customize the theme and style of this page to match your application’s look and feel.

Flyouts

The Windows 8.1 SDK provides a Flyout control that can be used to gather user information, display a message, prompt for confirmation, or provide menu options.

The Basics

The Flyout control enables users to dismiss the control simply by touching anywhere on the screen outside of the Flyout. You may customize the content of the Flyout control by displaying any elements that you see fit within a container control. You are not constricted to displaying static text alone. You can incorporate input fields, images, buttons, or any other rich content you so desire. You also may apply your application’s theme or custom styles to provide visual appeal to the control.

In the event that you want to display a list of menu options, the content of the Flyout control may be set to the MenuFlyout element. The MenuFlyout element enables you to define the list of options that will be presented to the user and to wire up events to handle the user’s selection. Menu items within a MenuFlyout may consist only of regular menu items, toggle menu items, and/or separator bars. We will demonstrate the use of the MenuFlyout element later in this section.

To perform custom actions when the Flyout control is loading, displayed, or dismissed, you may subscribe to the Flyout control’s Opening, Opened, or Closed events, respectively.

Usage and Syntax

Flyouts can be implemented within a page through a button, Application Bar button, or programmatically. To display a flyout when a button is tapped, simply include the desired Flyout markup within the Button element, as follows:

<Button>
   <Button.Flyout>
      <Flyout>
    <!-- include your desired content here -->
      </Flyout>
   </Button.Flyout>
</Button>

When the Flyout is associated with a button in this way, no additional code is needed to display the flyout. Tapping the button will automatically trigger the flyout to open.

If you want to control where the Flyout is rendered when the button is tapped, you may set the Flyout’s Placement property to one of the following enumerated values: Top, Bottom, Left, Right, Full. Setting the control’s Placement to one of the first four properties will ensure that it displays at the specified location in relation to its parent button. Setting Placement to Full will cause the Flyout to expand and display in the center of the screen, as illustrated in Figure 10-12.

9781430267768_Fig10-12.jpg

Figure 10-12. When the Flyout’s Placement property is set to Full, it will display center screen

You can also integrate a Flyout control within an AppBarButton using similar markup as follows:

<AppBarButton>
   <AppBarButton.Flyout>
      <!-- place desired content here -->
   </AppBarButton.Flyout>
</AppBarButton>

Just as with the button, incorporating a Flyout within an AppBarButton will cause the Flyout to display when the AppBarButton is tapped.

As mentioned earlier, you may be able to create a MenuFlyout to present the user with contextual options to take action on the current page, as shown in Listing 10-5. A MenuFlyout can contain only the following child elements:

  • MenuFlyoutItem: Displays a simple menu item. Use this menu item when an action must be taken immediately upon selection. Subscribe to the Click event to handle user selection.
  • ToggleMenuFlyoutItem: Displays a menu item that will appear with a check mark next to it when tapped. Use this menu item to provide the user with a choice of options. Monitor the value of the IsChecked property on the ToggleMenuFlyoutItem to determine whether the item has been selected.
  • MenuFlyoutSeparator: Displays a horizontal gray bar. It is not a functional menu item, and it is simply used to separate menu items into groups.

Programmatic Display

If you want to attach a Flyout to a FrameworkElement other than a button, you must declare the Flyout as a Resource, associate the Flyout control to the FrameworkElement using the FlyoutBase.FlyoutAttached property, and programmatically trigger the Flyout to display by calling the FlyoutBase.ShowAttachedFlyout method from the code-behind when the FrameworkElement is tapped.

For example, let’s say you wanted to create a card game where an Image control is used to display a card. When a special card is tapped, you want to provide the user with a list of options to enable them to decide how that card will be used in the game.

To associate a Flyout with an Image control, define your Flyout as a page resource and then associate the Flyout to the Image control, as shown in Listing 10-6.

In the Page’s code-behind file, call the FlyoutBase.ShowAttachedFlyout method, simply passing in the Image control.

private void OnSpecialCardTapped (object sender, TappedRoutedEventArgs e)
{
   FlyoutBase.ShowAttachedFlyout((FrameworkElement)sender);
}

And that’s all there is to it! With a few extra steps, you can easily associate Flyout controls to any FrameworkElement in your application.

Flyout Styles

Now that you know how to incorporate flyouts into your application, let’s take a closer look to see how the Flyout control can be customized to conform to the application’s theme.

FlyoutPresenter

The content within a Flyout control can be styled in the same way that you would style standard FrameworkElements within XAML. However, the Flyout control itself may not be styled directly. Instead, it must be styled by configuring its FlyoutPresenterStyle. The FlyoutPresenterStyle defines the overall appearance of the Flyout control. You will be able to customize the style of the control’s dependency properties, such as FontSize, Background, Foreground, and Padding to name just a few. When defining the FlyoutPresenterStyle, you must set its TargetType="FlyoutPresenter" and include setters for the dependency properties that you want to customize, as follows:

<Flyout>
    <Flyout.FlyoutPresenterStyle>
        <Style TargetType="FlyoutPresenter">
             <Setter Property="BorderBrush" Value="White" />
             <Setter Property="Background" Value="CornflowerBlue" />
             <Setter Property="Foreground" Value="White" />
                ...
        </Style>
    </Flyout.FlyoutPresenterStyle>
    <!-- Flyout content -->
</Flyout>

MenuFlyoutPresenter

Similar to the Flyout control, you may configure the style on the MenuFlyout using the MenuFlyoutPresenterStyle property, ensuring that the TargetType is set to MenuFlyoutPresenter.

<MenuFlyout>
    <MenuFlyout.MenuFlyoutPresenterStyle>
        <Style TargetType="MenuFlyoutPresenter">
        ...
        </Style>
    </MenuFlyout.MenuFlyoutPresenterStyle>
    <!-- Menu Flyout content -->
</Flyout>

Contracts

The Windows 8.1 SDK provides contracts that you can leverage within your application to interact with the native system features and functionality, such as sharing content between applications and integrating with the Settings menu.

Share Contract

The share contract enables applications to share data with and/or receive data from other applications in the form of plain text, links, and files. You can designate your application to participate as the share source, which will serve data to an application of the user’s choosing. Only those applications that are configured to serve as a share target will be available as an option with which to share data. You can also configure your application to serve as the target source. In this way, when a user selects to share data from an external application, such as Facebook or Instagram, your application will appear in the list as a target application that is available to receive the content.

To ensure that your application is configured to share data with other applications, you must add the Windows.ApplicationModel.DataTransfer namespace to your application page. Within your application page’s constructor, you must retrieve an instance of the DataTransferManager object and subscribe to its DataRequested event. The DataRequested event is triggered whenever the user invokes a share action through the Charms bar. Therefore, you will make use of this event to include any data that you want to share with any external applications.

Finally, the data you want to share must be passed through a DataRequest object. Note that the Title of the DataRequest object is a mandatory field and must be set. Listing 10-7 shows a basic example of configuring the main page of the application to participate in the share contract so that it can share data with external applications.

Listing 10-7 illustrates how easy it is to share text with external applications. However, what if you wanted to share an image? This does require a few extra lines of code; however, it is very straightforward.

To share an image, you must convert it into a RandomAccessStreamReference, which will then be passed to the DataRequest object through a call to the SetBitmap method, as shown in Listing 10-8.

In Listing 10-8, we are loading the image from a file that we packaged with the application by calling the GetFileAsync method. Notice that we are using the async/await operators. In this case, we need to request a deferral, since we are invoking an asynchronous process. To accomplish this, we call the GetDeferral method on the DataRequest object so that the application is able to load the image and generate the DataPackage asynchronously. We wrap up the request by calling the Complete method on the deferral object. Now when we run the application, we can invoke the Charms bar and click the Share button to share our image with an external application, as shown in Figure 10-13.

9781430267768_Fig10-13.jpg

Figure 10-13. The application’s custom share title and description is displayed in the Share Flyout along with applications that are share targets

Selecting an application from the list of available share targets will cause the application to load in a snapped page with the share data displayed in view, as shown in Figure 10-14.

9781430267768_Fig10-14.jpg

Figure 10-14. The share target application is loaded in a snapped pane with the shared data in view

Settings Contract

The settings contract enables you to integrate your application’s settings within the Settings flyout accessible from the Charms bar. By default, all Windows Store applications are designed with a default Settings pane and are configured to participate in the settings contract. You may include up to seven commands within the Settings pane. If you do not include a custom Settings flyout within your application, the default Settings pane will contain the name of the application, your publisher name, a command that will display a Settings flyout containing application permissions information, and a command that will enable users to rate your app. The “Rate and review” command is available only once the application is published to the Windows Store.

Summary

This chapter provided an overview of the design principles and features that should be considered when designing your Windows Store applications. You learned about how to design your application to adapt to different layouts and how to incorporate Windows 8.1 contracts within your application to provide an engaging user experience. We also discussed the use of flyouts to provide contextual menu options.

In the next chapter, we will discuss how to package your Windows applications for publication in the Windows Store.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.171.153