从新浪微博客户端看Windows Phone 7的开发

http://dev.yesky.com/329/11502829.shtml

新浪围脖@WPMind.com v0.1是由WPMind.com开发的第一个Windows Phone 7上的软件作品,即新浪微博客户端。它也应该是国内第一款Windows Phone 7上的新浪微博客户端。在接下来的一系列文章中,我将带领大家探讨探讨该软件开发过程中遇到的各种问题。



(1) 环境准备
作为一个开发人员,我很高兴的看到了微软这次对于Windows Phone 7所做的各种努力。其中当然不得不提的就是微软对于Windows Phone Developer Tools的免费发行
安装Windows Phone Developer Tools的系统需求为:
支持的操作系统: Windows 7,Windows Vista
    * Windows® Vista® (x86 and x64) ENU with Service Pack 2 – 除了Starter之外的任何版本
    * Windows 7 (x86 and x64) ENU(当然,中文的Win7上也能正常安装) – 除了Starter之外的任何版本
需要的硬件配置
    * Installation requires 3 GB of free disk space on the system drive.
    * 2 GB RAM
    * DirectX 10 capable graphics card with a WDDM 1.1 driver

除了Windows Phone Developer Tools之外,我还强烈建议安装Express Blend 4 Beta版,以及对应Windows Phone 7开发所需要的Expression Blend Add-in for Windows PhoneExpression Blend SDK for Windows Phone.
Expression Blend 是微软的 Expression Studio套件中的很重要的一个部分,它是用来做Silverlight设计的。通常是由UI设计师来使用它完成界面的布局以及各种动态/动画效果的实现。不过我还是建议开发人员也都安装上它,毕竟我相信很多时候你的身边并没有专门的UI设计师,这一切还都得要我们自己动手完成。

安装完Windows Phone Developer tools,我们会发现他已经安装好Visual Studio 2010 Express for Windows Phone,其中包含Windows Phone 7的模拟器和Silverlight for Windows Phone 以及Game Studio 4.0.

接下来打开Visual Studio 2010,工程类型里面有了Silverlight for Windows Phone和Game Studio 4.0的工程模板,这时候准备工作已经完成了。


参考:http://www.wpmind.com/dev/2010/03/29/what-you-should-know-for-windows-phone-7-development.html

(2)Hello World! - 初识开发环境
上一小节中,我们讲到了要开发Windows Phone 7的应用程序需要安装的工具。那么今天这一小节,我们就来看看怎样用这些工具来开发Windows Phone 7的应用程序。

首先,我们打开Visual Studio 2010 Express for Windows Phone。在工程模板里面我们会看到针对Silverlight for Windows Phone 有3种开发类型如下图所示:

第一种“Windows Phone Application”就是很普通的一个Windows Phone的Silverlight应用程序。而第二种“Windows Phone List Appliation”则给出一个简单的列表型窗体的示例工程。第三种“Windows Phone Class Library”则是一个普通的类库工程。

现在我们先输入工程名称建立一个普通的“Windows Phone Application”,则系统自动建立起该工程所需要的一些文件并打开默认的窗体设计器如下图所示:

左侧的ToolBox和我们以前常规的WinForm或者说.NET CF开发工具栏比较类似,都是一些常规的控件。右侧的上方是Solution Explorer,可以在里面管理工程中的文件,而右侧下方则是属性窗口,用来显示当前选中的控件属性(以及事件)。而窗体的中间部位则分为左右两栏左侧是所见即所得的窗体设计器,而右侧则为XAML文件编辑器。

请尝试着从左侧工具箱里面拖拽一个Button到窗体中间,然后双击这个“Button”则自动跳转到代码编辑器中生成的代码。那么还等待什么?请做一件任何一个程序员都会尝试的第一个程序吧,输入:

 
 
  1. MessageBox.Show("Hello world!"); 

然后按下F5键,则Visual Studio 2010会自动调用起Windows Phone 7的模拟器并将程序部署上去运行。点击模拟器中你的程序窗体上的Button,然后就得到了你的Windows Phone 7上的第一个Hello World程序。
好了,下来请在Visual Studio 2010中按下Shift+F5停止程序的运行回到编辑状态。让我们回过头来仔细看看Windows Phone 7的Hello World程序和普通的.NET Compact Framework程序都有什么不同吧。
首先是工程文件结构的不同,如下图所示:

对于VS2008中我们的.NET CF应用程序来说,每一个窗体由两个文件构成。一个普通的cs文件(例如Form1.cs)再加上一个Designer文件(例如Form1.Designer.cs)。这两个文件都是C#的代码文件,而且这两个C#文件其实是通过partial类技术来描述的同一个class。所不同的是,第一个cs文件里面通常放置界面上的一些逻辑处理,而第二个(Designer文件)里面放置的是窗体设计器上的布局的C#代码表现。
对于VS2010来说,每一个窗体也都是两个文件构成。但是第一个文件是一个普通的xaml文件,第二个是一个同名的.xaml.cs文件。第一个xaml文件里面都是界面布局(以及一些资源,动画等等)的定义,而cs文件里面放置的是你的逻辑的C#代码。

对于同样的一个Button的Click事件的处理,他们的方式也不同。对于.NET CF来说,它是通过常规的事件来处理,所以在代码中可以看到形如:

 
 
  1. this.button1.Click += new System.EventHandler(this.button1_Click); 

这样的事件注册代码。而对于VS2010中的XAML来说,他只是简单的在xaml中定义如下:

 
 
  1. <Button Content="Button"  Click="button1_Click" /> 

则在后端对应的cs文件中即可使用该click事件。

最后不得不提的是,由于Windows Phone 7使用的Silverlight来开发应用程序,所以很多控件也有了变化。下图为VS2008中一个.NET CF 3.5的工程中可用的控件和VS2010中的Windows Phone 7的控件对比列表:


怎么样,Windows Phone 7和以前的.NET Compact Framework的开发完全不一样了吧。 :)
今天的内容就先到这里,快点动手去写你自己的"Hello World"哦!

 

(3)Hello Sina!
上一小节中,我们讲解了Windows Phone 7的开发环境的一些基本支持。在本节内容中,我们将讲解如何通过新浪微博的API来获取微博信息,同时学会在Silverlight中控件的数据绑定。
要开发新浪微博应用程序,要做的第一步首先是去新浪微博开放平台申请一个APP Key。只有有了APP Key,你才能直接调用新浪微博API的各种接口。
今天首先要用到的是获取所有关注对象的微博信息列表的方法,它的地址是:http://api.t.sina.com.cn/statuses/friends_timeline.xml(或者http://api.t.sina.com.cn/statuses/friends_timeline.json),它将返回一个XML格式的数据列表。具体格式参见:http://open.t.sina.com.cn/wiki/i ... es/friends_timeline

首先,请打开Visual Studio 2010 Express for Windows Phone这个开发工具,并建立一个普通的"Windows Phone Application"。然后修改textBlockListTitle这个文本块的内容和字体大小来设定你的应用程序的标题。
接下来在该工程中添加一个Tools.cs类文件,里面我们会防止一些需要经常复用的工具方法类,代码如下:

 
 
  1. // Please use your sina AppKey and your sina micro blog username/password here.  
  2. const string appKey = "";   //请填写你的新浪APP Key  
  3. const string username = "";  //请填写你的新浪微博账号  
  4. const string password = "";  //请填写你的新浪微博密码  
  5.  
  6. public static string GetAppKey()  
  7. {  
  8.     return appKey;  
  9. }  
  10.  
  11. public static string GetUserName()  
  12. {  
  13.     return username;  
  14. }  
  15.  
  16. public static string GetPassword()  
  17. {  
  18.     return password;  
  19. }  
  20.  
  21. public static void InitWebClient(ref WebClient wc)  
  22. {  
  23.     wc = new WebClient();  
  24.     string username = GetUserName();  
  25.     string password = GetPassword();  
  26.     string usernameusernamePassword = username + ":" + password;  
  27.     wc.Credentials = new NetworkCredential(username, password);  
  28.     wc.Headers["Authorization"] = "Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(usernamePassword));  

对于最后一个方法InitWebClient,它是用来初始化我们的WebClient对象(用来做网络访问)。由于Sina的微博接口要求通过基本身份验证,所以通过该方法我们可以初始化一个基本身份验证的请求。即在Credentials里面添加用户名和密码,然后Header里面的Authorization里面加上经过Base64编码过后的用户密码信息。

然后添加一个MessageItem类,用于存放从服务器端获取的消息对象:

 
 
  1.       
  2. public class MessageItem  
  3.     {  
  4.         public string UserName { get; set; }  
  5.         public string Message { get; set; }  
  6.         public string ImageSource { get; set; }  
  7.         public string Time { get; set; }  
  8.     } 

接下来在主窗体(MainPage.xaml)里面添加一个ListBox放置在窗体中间,拖拽大小填充满整个主窗体的下半部分。然后在xaml代码部分修改这个ListBox的代码如下:

 
 
  1. <ListBox Height="651" HorizontalAlignment="Left" Margin="0,6,0,0" Name="listMain" VerticalAlignment="Top" Width="474"> 
  2.     <ListBox.ItemTemplate> 
  3.         <DataTemplate> 
  4.             <StackPanel Orientation="Horizontal" Background="{StaticResource TransparentBrush}" Margin="0,5"> 
  5.                 <Image Source="{Binding ImageSource}" Height="73" Width="73" VerticalAlignment="Top" Margin="8"/> 
  6.                 <StackPanel Width="360"> 
  7.                     <TextBlock Text="{Binding UserName}" Foreground="#FFED5A13" FontSize="28" /> 
  8.                     <TextBlock Text="{Binding Message}" TextWrapping="Wrap" FontSize="24" Foreground="White" /> 
  9.                     <TextBlock Text="{Binding Time}" Foreground="#FF1851C6" FontSize="20" /> 
  10.                 </StackPanel> 
  11.             </StackPanel> 
  12.         </DataTemplate> 
  13.     </ListBox.ItemTemplate> 
  14. </ListBox> 

不同与以前我们开发WinForm应用程序里面的ListBox或者ListView,我们看到这里ListBox的元素可以完全自定义。这里我们使用了ListBox.ItemTemplate,表明ListBox中的项目要通过模板来填充。而下面的<DataTemplate>则定义了每一个项目的表现形式。在这里,我们通过<StackPanel>来布局每个项目中的元素,即左侧是一个图片,用来绑定用户的头像,而右侧从上往下依次是用户名,发送的消息,以及发送消息的时间。

下面,我们将工程添加对于System.XML.Linq的引用以便使用LINQ来查询XML数据。然后在MainPage.xaml.cs中添加对于System.XML和System.XML.Linq的using.
然后修改MainPage.xaml.cs文件中的代码如下:

 
 
  1. private WebClient wcRefreshMyHome = null;  
  2. private string sinaAppKey = Tools.GetAppKey();  
  3.  
  4. private const int MaxMessageRecord = 20;  
  5. private const string RefreshHomeURL = "http://api.t.sina.com.cn/statuses/friends_timeline.xml";  
  6.  
  7. public MainPage()  
  8. {  
  9.     InitializeComponent();  
  10.     SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;  
  11.     Tools.InitWebClient(ref wcRefreshMyHome);  
  12.     wcRefreshMyHome.DownloadStringCompleted += new DownloadStringCompletedEventHandler(RefreshCompleted);  
  13. }  
  14.  
  15. private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)  
  16. {  
  17.     RefreshMyHomeList();  
  18. }  
  19.  
  20. void RefreshCompleted(object sender, DownloadStringCompletedEventArgs e)  
  21. {  
  22.     if (e.Error != null)  
  23.     {  
  24.         MessageBox.Show(e.Error.Message, "Error", MessageBoxButton.OK);  
  25.         return;  
  26.     }  
  27.  
  28.     XElement xmlSina = XElement.Parse(e.Result);  
  29.  
  30.     listMain.ItemsSource = from sina in xmlSina.Elements("status")  
  31.                               select new MessageItem  
  32.                               {  
  33.                                   ImageSource = sina.Element("user").Element("profile_image_url").Value,  
  34.                                   UserName = sina.Element("user").Element("screen_name").Value,  
  35.                                   Message = sina.Element("text").Value,  
  36.                                   Time = GetTime(sina.Element("created_at").Value)  
  37.                               };  
  38. }  
  39.  
  40. private string GetTime(string sinaFormat)  
  41. {  
  42.     string result = "";  
  43.     string[] strTemps = sinaFormat.Split(' ');  
  44.     strTemps[4] = "+01:00";  
  45.     result = String.Join(" ", strTemps);  
  46.  
  47.     DateTime dt = DateTime.ParseExact(result, "ddd MMM dd HH:mm:ff zzz yyyy", System.Threading.Thread.CurrentThread.CurrentCulture);  
  48.     result = dt.ToString("G");  
  49.     return result;  
  50. }  
  51.  
  52. private void RefreshMyHomeList()  
  53. {  
  54.     if (wcRefreshMyHome.IsBusy)  
  55.         wcRefreshMyHome.CancelAsync();  
  56.     wcRefreshMyHome.DownloadStringAsync(new Uri(RefreshHomeURL + "?count=" + MaxMessageRecord.ToString() + "&source=" + sinaAppKey), RefreshHomeURL);  

你会看到,我使用了一个WebClient对象wcRefreshMyHome,它将是我们用来访问Web服务器的主要对象。该对象只能采用异步模式来下载或者上传数据。所以,在MianPage的构造函数中我们通过该对象的DownloadStringCompletedEventHandler事件来添加对于下载结束的处理代码(即RefreshCompleted方法)。
而在RefreshCompleted中我的处理也很简单,只是简单的判断如果没有错误,则通过LINQ将数据填充到ListBox的数据源中。在这里需要注意的是,由于sina返回的数据中时间字段我们无法直接解析,所以我做了一些处理后得到正确的时间(GetTime方法)。

最终,我们在 PhoneApplicationPage_Loaded方法中加上RefreshMyHomeList的调用,即先判断当前的WebClient是否在下载,如果正在运行则取消之前的操作,然后重新进行异步下载。

好了,代码就到这里,按下F5试试看,你的程序已经正常的运行起来,并且成功的将你的新浪微博的好友信息下载了下来。:)

今天的这节内容就到这里,示例代码请参考附件中的demo2工程。

(4)使用AppBar
上一小节中,我们试着开发了新浪围脖客户端的最基本的功能 -- 列表关注对象的围脖消息。在今天的小节中,我们来看看在Windows Phone 7的应用程序中怎么样使用AppBar,即Windows Phone 7上最新的菜单系统。
首先我们来聊一聊Windows Phone发展史上的菜单系统的改变吧,下面这张图是早期的Pocket PC时期的经典的菜单样式(图片来自网络,如有侵权请通知我以便替换):

即屏幕的下方有一个菜单栏,在菜单栏上可以弹出多个菜单项,然后还可以有多个图标,点击图标也可以弹出子菜单。在菜单栏的最右侧是输入法切换图标。因为早期Pocket PC的设计中,微软几乎是按照普通的PC的用户体验来设计界面的。所以我们看到这种导航方式和PC的应用程序很类似,但是非常不适合手持设备来使用。尤其是菜单太密,要想精确点击,只能使用触笔而无法单手操作。

所以,到了Windows Mobile 5的时代,菜单做了点改变。菜单栏上的菜单只能放置两个,分别对应左软键和右软键,将输入法切换图标放在了两个软键菜单之间,这时候的用户体验略微好了一点点:


Windows Mobile 5的这种菜单风格一直用到了Windows Phone 6.5的时代。直到HTC在自家的HTC Sense界面中做了改变。HTC直接替换了系统的菜单系统,将不管是左软键还是右软键的菜单都统统拉升基本占满了整个屏幕的宽度,这样很大程度上便于了单手操作:


如果您细心的话,就会发现微软在Windows Phone 6.5的Internet Explorer中的菜单系统也做了点小小的改变,已经类似于Windows Phone 6.5.3版本中出现的菜单系统了。即,将原来左上角一直有的那个开始按钮放到了左下角,而将原来右上角的那个”X“或者”OK“按钮放到了窗体的右下角。然后将原来的左软键或者右软键菜单缩小为两个圆形的按钮(也可以是图片按钮或者文字按钮),中间仍然保持输入法切换按钮。


到了Windows Phone 7的时代,菜单系统延续了这种将用户操作全部放在了下方的设计,在窗体的下方区域称之为”App Bar“,在这里可以最多放置4个(在目前CTP版本中可以放置5个,但是经过用户反馈意见,在正式版本中将最多允许4个)按钮用来让用户执行最常用的操作。如果操作项不够的话,App Bar区域可以向上扩展,然后弹出更多的命令内容。如下图所示,放置了4个按钮,然后还可以弹出一些菜单项来。同时您应该注意到,这里的AppBar是可以设置透明度的。用户体验就好了很多。


在Windows Phone 7中要使用App Bar很容易。首先将工程中引用”Microsoft.Phone.Shell“。
然后在要加入AppBar的窗体中的XAML文件中加入形如下面的代码:

 
 
  1. <phoneNavigation:PhoneApplicationPage.ApplicationBar> 
  2.  
  3.         <shell:ApplicationBar Visible="True" IsMenuEnabled="True" ForegroundColor="Black" Opacity="0.5"> 
  4.  
  5.             <shell:ApplicationBar.Buttons> 
  6.  
  7.                 <shell:ApplicationBarIconButton x:Name="RefreshButton" IconUri="/Images/appbar.sync.rest.png" Click="ApplicationBarIconButton_Click" /> 
  8.  
  9.                 <shell:ApplicationBarIconButton x:Name="SayButton" IconUri="/Images/Say.png" Click="SayButton_Click" /> 
  10.  
  11.                 <shell:ApplicationBarIconButton x:Name="AtButton" IconUri="/Images/At.png" Click="AtButton_Click" /> 
  12.  
  13.                 <shell:ApplicationBarIconButton x:Name="ForwordButton" IconUri="/Images/Forword.png" Click="ForwordButton_Click" /> 
  14.  
  15.             </shell:ApplicationBar.Buttons> 
  16.  
  17.             <shell:ApplicationBar.MenuItems> 
  18.  
  19.                 <shell:ApplicationBarMenuItem Text="About" x:Name="AboutMenu" Click="AboutMenu_Click" /> 
  20.  
  21.             </shell:ApplicationBar.MenuItems> 
  22.  
  23.         </shell:ApplicationBar> 
  24.  
  25.     </phoneNavigation:PhoneApplicationPage.ApplicationBar> 


其中<shell:ApplicationBar>的Opacity属性用来设置AppBar的透明度,IsMenuEnabled属性用来设置是否需要附加的菜单项。
在<shell:ApplicationBar.Buttons>中来定义Button,而通过<shell:ApplicationBar.MenuItems>来定义附加的菜单项。
只要给Buton设置好IconUri图像属性,然后分别给它们设置Click属性即定义事件代码就好了。
用起来很简单不是么?

How to: Add an Application Bar to Your Application for Windows Phone

[Note: This topic is pre-release documentation and is subject to change in future releases. Blank topics are included as placeholders.]

4/22/2010

This topic shows how you can add an Application Bar to your Windows Phone application in XAML and in C#. To read about and download a sample application that uses the Application Bar, see Code Samples for Windows Phone.

Adding a Reference to the Application Bar Assembly

Before you can use the Application Bar in your application, you must add a reference to the correct assembly in your Windows Phone project.

To add a reference to the Application Bar dll

  1. Open a new or existing Windows Phone solution in Visual Studio.

  2. From the Project menu, select Add Reference…

  3. On the .NET tab, select the component name “Microsoft.Phone.Shell” and click OK.

Adding Icon Button Images to Your Windows Phone Project

Before you can use images for icon buttons in the Application Bar, you must add them to your project in Visual Studio.

To add icon button images to your project

  1. To create a subdirectory for your image files, in Solution Explorer, right-click the icon for your project and select Add and then New Folder. Rename the folder to “Images”.

  2. In Windows Explorer, copy your icon images into the Images folder under the directory from your project. For design guidelines about creating Application Bar icon images, see Application Bar Best Practices for Windows Phone.

  3. In Solution Explorer in Visual Studio right-click on the Images folder and select Add and then Existing Item…. Select one of your images or hold down Ctrl and select multiple images and then click Add.

  4. For each of your images, right-click the image in Solution Explorer and select Properties.

  5. Set the Build Action property to “Content” and set the Copy to Output property to “Copy always”.

Creating an Application Bar in XAML

You can create an Application Bar, assign it to a page, and set event handlers for icon buttons and menu items by adding a few elements to the XAML for your page. These steps assume that the page you are editing was generated using the default template by Visual Studio. The namespace prefixes associated with some of the elements may be different if you are using XAML from another source.

To create an Application Bar in XAML

  1. Open the XAML file for the page to which you will add the application bar. In Solution Explorer, right-click on the .xaml file for the page (by default, the main page for a new application is called “MainPage.xaml”) and select Open.

  2. Add a namespace declaration to set the namespace prefix for the Windows.Phone.Shell assembly to “shell:” by adding the following line to the phoneNavigation:PhoneApplicationPage element in the XAML.

    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone.Shell"
    
  3. Add a phoneNavigation:PhoneApplicationPage.ApplicationBar element inside the phoneNavigation:PhoneApplicationPage element. The phone application page object has a built-in ApplicationBar property and the contents of this element will define the Application Bar for this page.

    <phoneNavigation:PhoneApplicationPage.ApplicationBar>
    </phoneNavigation:PhoneApplicationPage.ApplicationBar>
    
  4. Inside the phoneNavigation:PhoneApplicationPage.ApplicationBar element, add a shell:ApplicationBar element. You can set any of the properties of the Application Bar in this element, but this example sets the visibility to True and the IsMenuEnabled property to True.

    <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
    </shell:ApplicationBar>
    
  5. Add a shell:ApplicationBar.Buttons element to the shell:ApplicationBar element. This element will contain the definitions for the Application Bar’s icon buttons.

    <shell:ApplicationBar.Buttons>
    </shell:ApplicationBar.Buttons>
    
  6. Now, add one or more shell:ApplicationBarIconButton elements to the shell:ApplicationBar.Buttons element. This represents the icon button. You will need to provide a URI to the image file for the icon button. If you placed your images in the folder specified previously in this topic, the paths in this example will be correct. Add a click handler by setting the Click attribute of the element. Visual Studio will display a context menu containing the text “<New Event Handler>” after you have typed “Click”. If you select this item, the tools will generate an event handler in the .cs file for this page. If you copy and paste the code, you will need to create the event handlers manually.

    <shell:ApplicationBarIconButton Click="ApplicationBarIconButton_Click" IconUri="/Images/button1.png"></shell:ApplicationBarIconButton>
    <shell:ApplicationBarIconButton Click="ApplicationBarIconButton_Click_1" IconUri="/Images/button2.png"></shell:ApplicationBarIconButton>
    
  7. Add a shell.ApplicationBar.MenuItems element as a child of the shell.ApplicationBar element. This element will contain the definitions for the Application Bar’s menu items.

    <shell:ApplicationBar.MenuItems>
    </shell:ApplicationBar.MenuItems>
    
  8. Now, add one or more shell:ApplicationBarMenuItem elements to the shell.ApplicationBar.MenuItems element. The Text attribute specifies the text that will be displayed in the menu. The click handler is set the same as for the icon buttons.

    <shell:ApplicationBarMenuItem Click="ApplicationBarMenuItem_Click" Text="MenuItem 1"></shell:ApplicationBarMenuItem>
    <shell:ApplicationBarMenuItem Click="ApplicationBarMenuItem_Click_1" Text="MenuItem 2"></shell:ApplicationBarMenuItem>
    

Now, when you run your application, the Application Bar will be displayed. The only thing left to do is implement your event handlers to take some action when the user taps on one of the icon buttons or menu items. The following code snippet shows the whole XAML element for the Application Bar. Remember that if you copy and paste this code, you will need to update the event handler declarations because the handler methods will not be autogenerated by Visual Studio.

<phoneNavigation:PhoneApplicationPage.ApplicationBar>
  <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
    <shell:ApplicationBar.Buttons>
      <shell:ApplicationBarIconButton x:Name=”button1” Click="button1_Click" IconUri="/Images/button1.png"></shell:ApplicationBarIconButton>
      <shell:ApplicationBarIconButton x:Name=”button2” Click="button2_Click" IconUri="/Images/button2.png"></shell:ApplicationBarIconButton>
    </shell:ApplicationBar.Buttons>
    <shell:ApplicationBar.MenuItems>
      <shell:ApplicationBarMenuItem x:Name=”menuItem1” Click="menuItem1_Click" Text="MenuItem 1"></shell:ApplicationBarMenuItem>
      <shell:ApplicationBarMenuItem x:Name=”menuItem2” Click="menuItem2_Click" Text="MenuItem 2"></shell:ApplicationBarMenuItem>
    </shell:ApplicationBar.MenuItems>
  </shell:ApplicationBar>
</phoneNavigation:PhoneApplicationPage.ApplicationBar>

The following code shows the format of the event handler for button or menu item Click events.

private void button1_Click(object sender, EventArgs e)
{
  // TODO: Add code that is run when the button is clicked.
}
Creating an Application Bar in C#

If you are more comfortable writing code in C# than working with XAML, you can add an Application Bar to your application entirely in C# without editing the XAML file at all.

To create an Application Bar in C#

  1. Open the C# file for the page to which you will add the application bar. In Solution Explorer, expand the node for the .xaml file for the page, right-click on the .xaml.cs file underneath the .xaml file and select Open.

  2. Add a using directive to the top of the .xaml.cs file and provide the name of the assembly that includes the Application Bar.

    using Microsoft.Phone.Shell;
    
  3. In the constructor for the page, initialize a new instance of the ApplicationBar property for the page.

    public MainPage()
    {
      InitializeComponent();
      ApplicationBar = new ApplicationBar();
    
  4. Set the Visible and IsMenuEnabled properties to True so that the Application Bar is visible and the menu is enabled when the page loads.

      ApplicationBar.IsVisible = true;
      ApplicationBar.IsMenuEnabled = true;
    
  5. Create one or more ApplicationBarIconButton objects. The constructor has a single argument, the Uri to the image for the icon button. Assign an event handler for the button’s Click event.

      ApplicationBarIconButton button1 = new ApplicationBarIconButton(new Uri("/Images/button1.png", UriKind.Relative));
      button1.Click += new EventHandler(button1_Click);
      ApplicationBarIconButton button2 = new ApplicationBarIconButton(new Uri("/Images/button2.png", UriKind.Relative));
      button2.Click += new EventHandler(button2_Click);
    
  6. Now, add the icon buttons to the Application Bar’s Buttons collection.

      ApplicationBar.Buttons.Add(button1);
      ApplicationBar.Buttons.Add(button2);
    
  7. Create one or more ApplicationBarMenuItem objects. The constructor has a single argument, the string displayed on the menu item. Assign an event handler for the menu item’s Click event.

      ApplicationBarMenuItem menuItem1 = new ApplicationBarMenuItem("MenuItem 1");
      menuItem1.Click += new EventHandler(menuItem1_Click);
      ApplicationBarMenuItem menuItem2 = new ApplicationBarMenuItem("MenuItem 2");
      menuItem2.Click += new EventHandler(menuItem2_Click);
    
  8. Now, add the menu items to the Application Bar’s MenuItems collection.

        ApplicationBar.MenuItems.Add(menuItem1);
      ApplicationBar.MenuItems.Add(menuItem2);
    

Now, your C# implementation of the Application Bar is complete. You will, however, need to write code in the Click event handlers for the icon buttons and menu items.

http://developer.windowsphone.com/

 

转载于:https://www.cnblogs.com/nio-nio/archive/2010/09/18/1830498.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值