现在的位置: 首页 > 综合 > 正文

wp7开发实例:Baby Sign Language

2013年12月13日 ⁄ 综合 ⁄ 共 9188字 ⁄ 字号 评论关闭
    These days, it’s quite common for parents to teach their babies a limited amount of sign language before they are old enough to talk. This ability to communicate simple wishes like “eat” or “milk” at an early age can reduce their frustration and, according
to some experts, even accelerate their language skills. Of course, to teach a baby sign language, the parent must learn some! That’s where this app comes in. 

    The Baby Sign Language app explains how to do eight common signs that are helpful for a baby to learn by showing an illustration and written instructions for each one. The signs are organized in a two-level list—the first level contains three categories,
and the second level contains the subset of signs belonging to the chosen category. 

    This project is similar to the auto-generated project you would get by creating a “Windows Phone Databound Application” project in Visual Studio. Both feature a main page with a list box, and a details page for displaying details about the selected item
from the list. Both also leverage data binding. 

    This app has two significant firsts for this book—it is the first app to use more than one page, and it is the first app to use data binding. It certainly won’t be the last to use these very-common features. The topic of navigating between multiple pages
is explored first, before examining the code for the Baby Sign Language app. Data binding is covered at the end of the chapter. 

   CODE:
  MainPage.xaml:

<phone:PhoneApplicationPage
    x:Class="WindowsPhoneApp.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
   xmlns:local="clr-namespace:WindowsPhoneApp"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="PortraitOrLandscape" 
    x:Name="Page" shell:SystemTray.IsVisible="True">

  <!-- An application bar with an "about" menu item and no buttons -->
  <phone:PhoneApplicationPage.ApplicationBar>
    <shell:ApplicationBar>
      <shell:ApplicationBar.MenuItems>
        <shell:ApplicationBarMenuItem Text="about" Click="AboutMenuItem_Click"/>
      </shell:ApplicationBar.MenuItems>
    </shell:ApplicationBar>
  </phone:PhoneApplicationPage.ApplicationBar>

  <Grid x:Name="LayoutRoot">
    <Grid.RowDefinitions>
      <RowDefinition Height="Auto"/>
      <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <!-- The standard header, with some tweaks -->
    <StackPanel Margin="24,16,0,12">
      <TextBlock Text="BABY SIGN LANGUAGE" Margin="-1,0,0,0"
                 FontFamily="{StaticResource PhoneFontFamilySemiBold}"
                 FontSize="{StaticResource PhoneFontSizeMedium}"/>
      <TextBlock x:Name="PageTitle" Text="categories" Margin="-3,-10,0,0"
                 FontFamily="{StaticResource PhoneFontFamilySemiLight}"
                 FontSize="{StaticResource PhoneFontSizeExtraExtraLarge}"/>
    </StackPanel>

    <Grid Grid.Row="1" Margin="{StaticResource PhoneHorizontalMargin}">
      <ListBox x:Name="ListBox" ItemsSource="{Binding}"
               SelectionChanged="ListBox_SelectionChanged">
        <ListBox.ItemTemplate>
          <!-- The data template controls how each item renders -->
          <DataTemplate>
            <!-- The border (and its explicit width) is only here
                 for the sake of the tilt effect -->
            <Border 
                    Width="{Binding ActualWidth, ElementName=Page}">
              <!-- The text block displays value of the
                   current item's Name property -->
              <TextBlock Text="{Binding Name}"
                         Margin="{StaticResource PhoneMargin}"
                         Style="{StaticResource PhoneTextExtraLargeStyle}"/>
            </Border>
          </DataTemplate>
        </ListBox.ItemTemplate>
      </ListBox>
    </Grid>
  </Grid>
</phone:PhoneApplicationPage>

  MainPage.xaml.cs:

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;

namespace WindowsPhoneApp
{
  public partial class MainPage : PhoneApplicationPage
  {
    int categoryIndex = -1;

    public MainPage()
    {
      InitializeComponent();
      this.Loaded += MainPage_Loaded;
    }

    void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
      if (this.ListBox.Items.Count > 0)
        return; // We already added the data.
                // (We must be navigating back to this page.)

      if (this.categoryIndex == -1)
      {
        // This is the root page. Fill the list box with the categories.
        this.DataContext = Data.Categories;
      }
      else
      {
        // This is a page for a specific category.
        // Fill the list box with the category's items.
        this.DataContext = Data.Categories[this.categoryIndex].Signs;
      }
    }

    void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
      if (this.ListBox.SelectedIndex == -1)
        return; // The selection was cleared, so do nothing

      if (this.categoryIndex == -1)
      {
        // This is the root page, so the selection is a category. Navigate to a
        // new instance of this page initialized with the chosen category.
        this.NavigationService.Navigate(new Uri("/MainPage.xaml?categoryIndex=" +
          this.ListBox.SelectedIndex, UriKind.Relative));
      }
      else
      {
        // We're already on the page for a specific category, so the selection is
        // a sign. Navigate to the details page for this sign.
        this.NavigationService.Navigate(new Uri(
          "/DetailsPage.xaml?categoryIndex=" + this.categoryIndex +
          "&signIndex=" + this.ListBox.SelectedIndex, UriKind.Relative));
      }

      // Clear the selection so the same item can be selected
      // again on subsequent visits to this page
      this.ListBox.SelectedIndex = -1;
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
      base.OnNavigatedTo(e);
      if (this.NavigationContext.QueryString.ContainsKey("categoryIndex"))
      {
        // This is the page for a specific category.
        // Remember its index and display its name.
        this.categoryIndex = int.Parse(
          this.NavigationContext.QueryString["categoryIndex"]);
        this.PageTitle.Text = Data.Categories[this.categoryIndex].Name;
      }
    }

    void AboutMenuItem_Click(object sender, EventArgs e)
    {
      this.NavigationService.Navigate(new Uri(
        "/Shared/About/AboutPage.xaml?appName=Baby Sign Language",
        UriKind.Relative));
    }
  }
}

  Data/Sign.cs:


using System;

namespace WindowsPhoneApp
{
  public class Sign
  {
    public string Name { get; private set; }
    public Uri ImageUri { get; private set; }
    public string Description { get; private set; }

    public Sign(string name, Uri imageUri, string description)
    {
      this.Name = name;
      this.ImageUri = imageUri;
      this.Description = description;
    }
  }
}

Data/Category.cs:


namespace WindowsPhoneApp
{
  public class Category
  {
    public string Name { get; private set; }
    public IList<Sign> Signs { get; private set; }

    public Category(string name, IList<Sign> signs)
    {
      this.Name = name;
      this.Signs = signs;
    }
  }
}

Data/Data.cs:


using System;

namespace WindowsPhoneApp
{
  public class Data
  {
    public static readonly Category[] Categories = {
      new Category("eating & drinking",
        new Sign[] {
          new Sign("eat", new Uri("Images/eat.png", UriKind.Relative), "Mimic the motion of eating food out of your hand by moving your closed fingertips toward and away from your mouth a few times."),
          new Sign("milk", new Uri("Images/milk.png", UriKind.Relative), "Pretend that you're milking a cow by squeezing and loosening your fist a few times."),
          new Sign("water", new Uri("Images/water.png", UriKind.Relative), "Make the letter \"W\" and tap it on your mouth or chin a few times.")
        }),
      new Category("people",
        new Sign[] {
          new Sign("daddy", new Uri("Images/daddy.png", UriKind.Relative), "Open your hand and tap your thumb on your forehead a few times. (Male signs are made above the nose.)"),
          new Sign("mommy", new Uri("Images/mommy.png", UriKind.Relative), "Open your hand and tap your thumb on your chin a few times. (Female signs are made below the nose.)")
        }),
      new Category("other",
        new Sign[] {
          new Sign("all done", new Uri("Images/alldone.png", UriKind.Relative), "Hold up and open both hands, then twist your wrists back and forth."),
          new Sign("more", new Uri("Images/more.png", UriKind.Relative), "Close your fingertips and thumb on both hands, and touch them together."),
          new Sign("play", new Uri("Images/play.png", UriKind.Relative), "Make the letter \"Y\" with each hand and twist your wrists back and forth.")
        })
    };
  }
}

DetailsPage.xaml:


<phone:PhoneApplicationPage 
    x:Class="WindowsPhoneApp.DetailsPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="PortraitOrLandscape"
    shell:SystemTray.IsVisible="True">
  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="Auto"/>
      <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <!-- The standard header, with some tweaks -->
    <StackPanel Margin="24,16,0,12">
      <TextBlock Text="BABY SIGN LANGUAGE" Margin="-1,0,0,0"
                 FontFamily="{StaticResource PhoneFontFamilySemiBold}"
                 FontSize="{StaticResource PhoneFontSizeMedium}"/>
      <TextBlock Text="{Binding Name}" Margin="-3,-10,0,0"
                 FontFamily="{StaticResource PhoneFontFamilySemiLight}"
                 FontSize="{StaticResource PhoneFontSizeExtraExtraLarge}"/>
    </StackPanel>

    <ScrollViewer Grid.Row="1">
      <StackPanel Margin="{StaticResource PhoneHorizontalMargin}">
        <Image Source="{Binding ImageUri}"/>
        <TextBlock Text="{Binding Description}" Margin="{StaticResource PhoneMargin}" TextWrapping="Wrap"/>
      </StackPanel>
    </ScrollViewer>
  </Grid>
</phone:PhoneApplicationPage>

DetailsPage.xaml.cs:


using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;

namespace WindowsPhoneApp
{
  public partial class DetailsPage : PhoneApplicationPage
  {
    public DetailsPage()
    {
      InitializeComponent();
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
      // Make sure the two indices are passed along
      if (!this.NavigationContext.QueryString.ContainsKey("categoryIndex") ||
          !this.NavigationContext.QueryString.ContainsKey("signIndex"))
        return;

      // Convert the query string parameters into integers
      int categoryIndex = 
        int.Parse(this.NavigationContext.QueryString["categoryIndex"]);
      int signIndex = int.Parse(this.NavigationContext.QueryString["signIndex"]);

      // Fetch the data
      Sign sign = Data.Categories[categoryIndex].Signs[signIndex];

      // Update the UI
      this.DataContext = sign;
    }
  }
}
  download address:

抱歉!评论已关闭.