在WP7中显示员工xml数据(从网络获取数据) 转

转自: http://www.developer.nokia.com/Community/Wiki/%E5%9C%A8WP7%E4%B8%AD%E6%98%BE%E7%A4%BA%E5%91%98%E5%B7%A5xml%E6%95%B0%E6%8D%AE




本文展示了如何在Windows Phone中显示xml数据。

简介

本文展示了如何从服务器获取有关员工的xml数据,并在Windows Phone中显示。加载的xml数据会在一个ListBox中显示(图1),选中的用户的详细信息则显示在一个单独的页面上(图2),你也可以给选中的用户打电话发短信。

Employees in ListBox Employees Details Call to selected Employee Send SMS message to selected Employee Send Email to selected Employee

在服务器上准备数据

本示例使用xml做数据。请准备好如下格式的xml文件和照片。

PTM EmployeesXML.jpg

请给你的员工准备一些漂亮的照片,和xml文件放在同一目录下。

Windows Phone 7.1 SDK

为了给Windows Phone设备做开发,你需要安装Windows Phone 7.1 SDK。可以自这里下载最新版的SDK。

Windows Phone程序

现在开始创建Windows Phone程序。打开Microsoft Visual studio,创建一个新项目,选择Windows Phone Application模板。本文使用C#。

PTM EmployeeProject.png

在Windows Phone中解析xml

有很多方式可以解析xml数据。本文使用XML Deserialization将xml文件传给一个deserializer。你需要引用System.Xml.Serialization和System.Xml.Linq。在Solutions Explorer中右击"References",选择"Add new Reference..."

PTM EmployeesSolutionExplorer.png

Employees类

员工的数据会从xml文件加载,所有信息存到Employee类中。

在你的项目中创建一个Employees类: 1. 右击Solutions Explorer 2. 选择Add然后Class...

Name: Employees.cs 点击 Add.

using System;
using System.Xml.Serialization;
using System.Collections.ObjectModel;
 
namespace Employees
{
    [XmlRoot("root")]
    public class Employees
    {
        [XmlArray("employees")]
        [XmlArrayItem("employee")]
        public ObservableCollection<Employee> Collection { get; set; }
    }
}

像你在xml文件中看到的那样,在Employees类中用root做根元素,包含所有员工(你必须添加using System.Xml.Serialization)。 之后写上employees数组,包含一个employee项目。所有employee项目在一个ObservableCollection中存储 (你必须添加using System.Collections.ObjectModel)

Employee类

xml数据中每个员工都有像firstname, lastname, title这样的元素。你需要将它们标记为XMLElement。记住添加using System.Xml.Serialization。

创建一个Employee类: 1. 右击Solutions Explorer 2. 选择Add然后Class...

Name: Employee.cs 点Add.

using System;
using System.Xml.Serialization;
 
namespace Employees
{
    public class Employee
    {
        [XmlElement("firstName")]
        public string firstName { get; set; }
 
        [XmlElement("lastName")]
        public string lastName { get; set; }
 
        [XmlElement("title")]
        public string title { get; set; }
 
        [XmlElement("phone")]
        public string phone { get; set; }
 
        [XmlElement("email")]
        public string email { get; set; }
 
        [XmlElement("room")]
        public string room { get; set; }
 
        [XmlElement("picture")]
        public string picture { get; set; }
 
        [XmlElement("info")]
        public string info { get; set; }
    }
}

MainPage.xaml

所有的员工都在一个ListBox中显示。

Employees in ListBox

加载照片

在Windows Phone中从网上下载图片会有一个小问题。有些assembly解决了这个问题。PhonePerformance就是用于解决该问题的的assembly (你可以自here下载编译好的PhonePerformance assembly和它的源代码). 你必须下载并解压它。将PhonePerformance.dll复制到项目并在Solution Explorer.中添加引用。

你可能会得到一个warning要求unblock PhonePerformance.dll assembly (因为它是从网上下载的).关闭Visual Studio,打开Windows Exlorer找到PhonePerformance.dll文件,打开file properties点击Unblock.

PTM EmployeesPhonePerformanceProperties.jpg

程序标题

将标题改得更合适一些。

<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
	<TextBlock x:Name="ApplicationTitle" Text="My Company" Style="{StaticResource PhoneTextNormalStyle}"/>
	<TextBlock x:Name="PageTitle" Text="Employees" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>

用ListBox显示员工

每个员工都是ListBox中的一项。每项高130 px。照片占据100 px,employees name, title和room显示在照片右边。我们会将数据从代码绑定至ListBox。(今后在MainPage.xaml.cs你可以看到更多关于数据绑定的信息). PhonePerformance.dll 用于加载照片(看Image元素: Image delay:LowProfileImageLoader.UriSource="{Binding picture}"). 记得在phone:PhoneApplicationPage元素上添加xmlns:delay="clr-namespace:Delay;assembly=PhonePerformance"。

当用户选中某项时,一个Employee页面会显示。(调用employeesList_SelectionChanged方法). EmployeePage.xaml之后会有说明.

<phone:PhoneApplicationPage
    x:Class="Employees.MainPage"
    ....
    xmlns:delay="clr-namespace:Delay;assembly=PhonePerformance"
<ListBox x:Name="employeesList"  
                     SelectionChanged="employeesList_SelectionChanged">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <Grid Height="130">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="100"/>
                                <ColumnDefinition Width="*"/>
                            </Grid.ColumnDefinitions>
                            <Image delay:LowProfileImageLoader.UriSource="{Binding picture}" 
                                   Grid.Column="0" 
                                   Width="97" 
                                   Height="125" 
                                   VerticalAlignment="Center" 
                                   HorizontalAlignment="Center" 
                                   Margin="6"/>
                            <StackPanel Margin="10,15,0,0"
                                        Grid.Column="1"
                                        Height="60"
                                        Orientation="Horizontal" 
                                        VerticalAlignment="Top">
                                <TextBlock Text="{Binding lastName}" 
                                           FontSize="30" />
                                <TextBlock Text=" " />
                                <TextBlock Text="{Binding firstName}" 
                                           FontSize="30"/>
                            </StackPanel>
                            <StackPanel Margin="0,50,0,0"
                                        Grid.Column="1"
                                        VerticalAlignment="Center">
                                <TextBlock Grid.Column="1" 
                                       Text="{Binding title}" 
                                       Style='{StaticResource PhoneTextSubtleStyle}'
                                       />
                                <TextBlock Grid.Column="1" 
                                       Text="{Binding room, StringFormat='Room: \{0\}'}" 
                                       Style='{StaticResource PhoneTextSubtleStyle}'
                                       />
                            </StackPanel>
                        </Grid>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

MainPage.xaml.cs

MainPage的Code behind从服务器下载xml数据,解析并创建Employee类,在将数据绑定到UI.

从服务器下载xml数据

在MainPage的构造函数中在InitializeComponent()之后,首先检查网络连接状况。如果网络可用,就从服务器下载xml数据。

public MainPage()
        {
            InitializeComponent();
            // is there network connection available
            if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
                MessageBox.Show("No network connection available!");
                return;
            }
            // start loading XML-data
            WebClient downloader = new WebClient();
            Uri uri = new Uri("http://your.domain.url.here/employees.xml", UriKind.Absolute);
            downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(EmployeesDownloaded);
            downloader.DownloadStringAsync(uri);
        }

xml数据下载好后就解析它。

void EmployeesDownloaded(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Result == null || e.Error != null)
            {
                MessageBox.Show("There was an error downloading the XML-file!");
            }
            else
            {
                // Deserialize if download succeeds
                XmlSerializer serializer = new XmlSerializer(typeof(Employees));
                XDocument document = XDocument.Parse(e.Result);
                // get all the employees
                Employees employees = (Employees) serializer.Deserialize(document.CreateReader());
                // bind data to ListBox
                employeesList.ItemsSource = employees.Collection;
            }
        }

当用户选中ListBox中的一项时, employeesList_SelectionChanged会被调用。在这里首先找到Application并将选中的用户存在那里。这是在两个页面中共享数据的一种方法。之后,显示一个新页面。EmployeePage.xaml 会在本文后半部创建。

// selection in EmployeeList is changed
private void employeesList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
            var app = App.Current as App;
            app.selectedEmployee = (Employee) employeesList.SelectedItem;
            this.NavigationService.Navigate(new Uri("/EmployeePage.xaml", UriKind.Relative));
}

现在所有员工都应该可以在MainPage中看到。

App.xaml.cs

在前面一章我们将员工信息存在了App类中。现在需要修改App.xaml.cs文件(添加selectedEmployee):

// selected employee from EmployeeList
       public Employee selectedEmployee { get; set; }

EmployeePage.xaml

Create a new Page to your Project

Employee's detailed information is shown a new Employee Page. To create a new Page to your project, right click your project in Solution Exloperer and select Add, New Item... Select Windows Phone Portrait Page and name it to EmployeePage.xaml

PTM EmployeePage.png

Employee页面设计

在右边你可以看到Employee Detail页面的设计模式。

Employees Details Employees Details Design Page

Company name和Page title都像Main Page中一样显示。你可以自己修改该它们。

<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="My Company" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="Employees" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

接下来是员工的照片,last和first name,还有title和room.StackPanel用于组织控件。

<Grid Height="130" VerticalAlignment="Top">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="100"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <Image x:Name="image" 
                                   Grid.Column="0" 
                                   Width="97" 
                                   Height="125" 
                                   VerticalAlignment="Center" 
                                   HorizontalAlignment="Center" 
                                   Margin="6"/>
                <StackPanel Margin="10,15,0,0"
                                        Grid.Column="1"
                                        Height="60"
                                        Orientation="Horizontal" 
                                        VerticalAlignment="Top">
                    <TextBlock x:Name="lastName" FontSize="30" />
                    <TextBlock Text=" " />
                    <TextBlock x:Name="firstName" FontSize="30"/>
                </StackPanel>
                <StackPanel Margin="0,50,0,0"
                            Grid.Column="1"
                            VerticalAlignment="Center">
                    <TextBlock Grid.Column="1" 
                               x:Name="title" 
                               Style='{StaticResource PhoneTextSubtleStyle}'
                               />
                    <TextBlock Grid.Column="1" 
                               x:Name="room" 
                               Style='{StaticResource PhoneTextSubtleStyle}'
                               />
                </StackPanel>
            </Grid>

用户可以通过点击电话号码给选中的员工打电话发短信。这时候ManipulationStarted事件会产生。你可以写事件处理程序.

<Grid Height="50" VerticalAlignment="Top" Margin="0,150"
                  ManipulationStarted="phone_ManipulationStarted">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <TextBlock x:Name="phone" VerticalAlignment="Center" FontSize="24"/>
                <Image Source="Images/call.png" HorizontalAlignment="Right"/>
            </Grid>
 
            <Grid Height="50" VerticalAlignment="Top" Margin="0,210"
                  ManipulationStarted="sms_ManipulationStarted">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <TextBlock x:Name="sms" VerticalAlignment="Center" FontSize="24"/>
                <Image Source="Images/msg.png" HorizontalAlignment="Right"/>
            </Grid>
 
            <Grid Height="50" VerticalAlignment="Top" Margin="0,270"
                  ManipulationStarted="mail_ManipulationStarted">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <TextBlock x:Name="mail" VerticalAlignment="Center" FontSize="24"/>
                <Image Source="Images/mail.png" HorizontalAlignment="Right"/>
            </Grid>

选中员工的详细信息会显示在屏幕底部。

<TextBlock x:Name="info" TextWrapping="Wrap"
                       FontSize="16" FontStyle="Italic"
                       VerticalAlignment="Bottom"
                       Margin="20,20,20,20"/>

本示例中我们用图画显示打电话,发短信,发邮件的按钮。你也可以用你自己的图画。首先在Solution Explorer 创建一个新文件夹。 (取名为Images). 将你的图画复制到那里. Solution Explorer中右击Images文件夹,选择Add, Existing Item...

PTM EmployeeImages.png

EmployeePage.xaml.cs

Employee Page的Code behind首先从App类取得员工数据,然后将信息显示在UI上.

// selected Employee
Employee employee;
 
public EmployeePage()
        {
            InitializeComponent();
 
            // get selected employee from App Class
            var app = App.Current as App;
            employee = app.selectedEmployee;
 
            // show employee details in page
            lastName.Text = employee.lastName;
            firstName.Text = employee.firstName;
            title.Text = employee.title;
            room.Text = "Room: " + employee.room;
            image.Source = new BitmapImage(new Uri(employee.picture, UriKind.RelativeOrAbsolute));
            mail.Text = "Email: " + employee.email;
            sms.Text = "SMS: " + employee.phone;
            phone.Text = "Call: " + employee.phone;
            info.Text = employee.info;
        }

当用户想给该员工打电话时,phone_ManipulationStarted方法会被调用(记得添加using Microsoft.Phone.Tasks)

private void phone_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show("Make a phone call?", employee.lastName + " " + employee.firstName, MessageBoxButton.OKCancel);
            if (result == MessageBoxResult.OK)
            {
                // make a phone call
                PhoneCallTask phoneTask = new PhoneCallTask();
                phoneTask.DisplayName = employee.lastName + " " + employee.firstName;
                phoneTask.PhoneNumber = employee.phone;
                phoneTask.Show();
            }
        }

当用户想给该员工发短信时,sms_ManipulationStarted方法会被调用

private void sms_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show("Send SMS message?", employee.lastName + " " + employee.firstName, MessageBoxButton.OKCancel);
            if (result == MessageBoxResult.OK)
            {
                // sms
                SmsComposeTask composeSMS = new SmsComposeTask();
                composeSMS.Body = "Edit your message";
                composeSMS.To = employee.phone;
                composeSMS.Show();
            }
        }

当用户想给该员工发邮件时,mail_ManipulationStarted方法会被调用

private void mail_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show("Send Email?", employee.lastName + " " + employee.firstName, MessageBoxButton.OKCancel);
            if (result == MessageBoxResult.OK)
            {
                // sähköposti
                EmailComposeTask emailcomposer = new EmailComposeTask();
                emailcomposer.To = "<a href=\"mailto:" + employee.email + "\">" + employee.email + "</a>";
                emailcomposer.Subject = "Edit your Subject";
                emailcomposer.Body = "Edit your Message";
                emailcomposer.Show();
            }
        }

总结

在Windows Phone中使用xml很简单。希望本文对初学Visual Studio的人有用。最后,这里是本文的源代码: File:PTM Employees.zip

Comments

(no comments yet)



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值