与众不同 windows phone (26) - Contacts and Calendar(联系人和日历)

[索引页]
[源码下载]


与众不同 windows phone (26) - Contacts and Calendar(联系人和日历)



作者:webabcd


介绍
与众不同 windows phone 7.5 (sdk 7.1) 之联系人和日历

  • 获取联系人相关数据
  • 获取日历相关数据



示例
1、演示如何获取联系人相关数据
ContactPictureConverter.cs

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using Microsoft.Phone.UserData;
using System.IO;
using Microsoft.Phone;

namespace Demo.ContactsAndCalendar
{
    public class ContactPictureConverter : System.Windows.Data.IValueConverter
    {
        // 提取 Contact 中的图片,将图片转换成 WriteableBitmap 类型对象并返回
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Contact contact = value as Contact;
            if (contact == null) 
                return null;

            // 将联系人图片转换成 WriteableBitmap 类型的对象,并返回此对象
            Stream imageStream = contact.GetPicture();
            if (imageStream != null)
                return PictureDecoder.DecodeJpeg(imageStream);

            return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

ContactsDemo.xaml

<phone:PhoneApplicationPage 
    x:Class="Demo.ContactsAndCalendar.ContactsDemo"
    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:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d" d:DesignHeight="768" d:DesignWidth="480"
    shell:SystemTray.IsVisible="True"
    
    xmlns:converter="clr-namespace:Demo.ContactsAndCalendar">

    <phone:PhoneApplicationPage.Resources>
        <converter:ContactPictureConverter x:Key="ContactPictureConverter" />
    </phone:PhoneApplicationPage.Resources>

    <Grid x:Name="LayoutRoot" Background="Transparent">
        <StackPanel Orientation="Vertical">

            <TextBlock Name="lblMsg" />

            <Button Name="btnGetData" Content="获取联系人相关数据" Click="btnGetData_Click" />

            <!--用于绑定设备中的全部联系人信息,并显示联系人的第一个 email 地址和第一个电话号码-->
            <ListBox Name="listBoxContacts" ItemsSource="{Binding}" Height="200" Margin="0,15,0,0" >
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="{Binding Path=EmailAddresses[0].EmailAddress, Mode=OneWay}" />
                            <TextBlock Text="{Binding Path=PhoneNumbers[0].PhoneNumber, Mode=OneWay}" />
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

            <!--用于绑定设备中联系人 email 地址带“hotmail”的联系人数据,并显示联系人的图片及联系人的名称-->
            <ListBox Name="listBoxContactsWithHotmail" ItemsSource="{Binding}" Height="200" Margin="0,15,0,0">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <Border BorderThickness="2" HorizontalAlignment="Left" BorderBrush="{StaticResource PhoneAccentBrush}" >
                                <Image Source="{Binding Converter={StaticResource ContactPictureConverter}}" Width="48" Height="48" Stretch="Fill" />
                            </Border>
                            <TextBlock Text="{Binding Path=DisplayName, Mode=OneWay}" />
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

        </StackPanel>
    </Grid>

</phone:PhoneApplicationPage>

ContactsDemo.xaml.cs

/*
 * 演示如何获取设备中的联系人数据
 * 
 * Contacts - 用于获取联系人数据的类
 *     Accounts - 联系人数据可能来自用户的不同帐户,Accounts 就是用来获取这个不同账户的,即数据源集合(只读属性,返回 Account 对象的集合)
 *     SearchAsync(string filter, FilterKind filterKind, object state) - 开始异步搜索联系人数据
 *         string filter - 筛选关键字
 *             当 filterKind 设置为 DisplayName, EmailAddress, PhoneNumber 时指定筛选关键字
 *             当 filterKind 设置为 None, PinnedToStart 时此值无用,直接写 String.Empty 就好
 *         FilterKind filterKind - 筛选器的类别(Microsoft.Phone.UserData.FilterKind 枚举)
 *             FilterKind.None - 返回全部联系人数据
 *             FilterKind.PinnedToStart - 返回已固定到开始屏幕的联系人数据
 *             FilterKind.DisplayName - 按名称搜索
 *             FilterKind.EmailAddress - 按 email 地址搜索
 *             FilterKind.PhoneNumber - 按电话号码搜索
 *         object state - 异步过程中的上下文
 *     SearchCompleted - 搜索完成时所触发的事件(事件参数 ContactsSearchEventArgs)
 * 
 * ContactsSearchEventArgs
 *     Filter - 筛选关键字
 *     FilterKind - 筛选器的类别
 *     Results - 返回搜索结果,Contact 对象的集合
 *     State - 异步过程中的上下文
 *     
 * Contact - 联系人
 *     Accounts - 与此联系人关联的数据源集合
 *       Addresses - 与此联系人关联的地址数据集合
 *       Birthdays - 与此联系人关联的生日数据集合
 *       Children - 子女
 *       Companies - 公司
 *       CompleteName - 联系人全称(包含诸如名字、职称和昵称之类的信息)
 *       DisplayName - 显示名称
 *       EmailAddresses - email 地址
 *       IsPinnedToStart - 是否固定到了开始屏幕
 *       Notes - 备注
 *       PhoneNumbers - 电话号码
 *       SignificantOthers - 与此联系人关联的重要他人
 *       Websites - 网站
 * 
 * Account - 账户
 *     Name - 账户名称
 *     Kind - 账户的种类(Microsoft.Phone.UserData.StorageKind 枚举)
 *         Phone, WindowsLive, Outlook, Facebook, Other
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

using Microsoft.Phone.UserData;

namespace Demo.ContactsAndCalendar
{
    public partial class ContactsDemo : PhoneApplicationPage
    {
        public ContactsDemo()
        {
            InitializeComponent();
        }

        private void btnGetData_Click(object sender, RoutedEventArgs e)
        {
            // 实例化 Contacts,注册相关事件
            Contacts contacts = new Contacts();
            contacts.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(contacts_SearchCompleted);

            // 指定搜索内容及搜索方式,开始异步搜索联系人信息
            contacts.SearchAsync(String.Empty, FilterKind.None, null);

            lblMsg.Text = "数据加载中,请稍后。。。";
            btnGetData.IsEnabled = false;
        }

        void contacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
        {
            try
            {
                // 绑定联系人数据
                listBoxContacts.DataContext = e.Results;

                // 绑定联系人 email 地址带“hotmail”的联系人数据
                var hotmailContacts = from c in e.Results
                                      from ContactEmailAddress a in c.EmailAddresses
                                      where a.EmailAddress.Contains("hotmail")
                                      select c;
                listBoxContactsWithHotmail.DataContext = hotmailContacts;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

            this.Dispatcher.BeginInvoke(delegate
            {
                lblMsg.Text = "数据加载完毕,共有联系人数据 " + e.Results.Count().ToString() + "";
                btnGetData.IsEnabled = true;
            });
        }
    }
}


2、演示如何获取日历相关数据
CalendarDemo.xaml

<phone:PhoneApplicationPage 
    x:Class="Demo.ContactsAndCalendar.CalendarDemo"
    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:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d" d:DesignHeight="768" d:DesignWidth="480"
    shell:SystemTray.IsVisible="True">

    <Grid x:Name="LayoutRoot" Background="Transparent">
        <StackPanel Height="Auto" Width="Auto" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" >

            <TextBlock Name="lblMsg" />

            <Button Name="btnGetData" Content="获取日历相关数据" Click="btnGetData_Click" />

            <!--用于绑定日历数据,并显示约会主题-->
            <ListBox Name="listBoxCalendar" ItemsSource="{Binding}" Height="200" Margin="0,15,0,0" >
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Path=Subject, Mode=OneWay}" />
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

            <!--用于绑定日历数据(只绑定主日历数据),并显示约会主题-->
            <ListBox Name="listBoxCalendarPrimary" ItemsSource="{Binding}" Height="200" Margin="0,15,0,0" >
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Path=Subject, Mode=OneWay}" />
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

        </StackPanel>
    </Grid>

</phone:PhoneApplicationPage>

CalendarDemo.xaml.cs

/*
 * 演示如何获取设备中的日历数据
 * 
 * Appointments - 用于获取日历约会数据的类
 *     Accounts - 日历约会数据可能来自用户的不同帐户,Accounts 就是用来获取这个不同账户的,即数据源集合(只读属性,返回 Account 对象的集合)
 *     SearchAsync(DateTime startTimeInclusive, DateTime endTimeInclusive, int maximumItems, Account account, Object state) - 开始异步搜索日历约会数据
 *         startTimeInclusive - 指定搜索范围:开始时间
 *         endTimeInclusive - 指定搜索范围:结束时间
 *         maximumItems - 指定返回约会数据的最大数量
 *         account - 指定约会数据的来源账户(不指定的话则全账户搜索)
 *         state - 异步过程中的上下文
 *     SearchCompleted - 搜索完成时所触发的事件(事件参数 AppointmentsSearchEventArgs)
 *     
 * AppointmentsSearchEventArgs
 *     StartTimeInclusive - 搜索范围的开始时间
 *     EndTimeInclusive - 搜索范围的结束时间
 *     Results - 返回搜索结果,Appointment 对象的集合
 *     State - 异步过程中的上下文
 *     
 * Appointment - 约会
 *     Account - 与此约会关联的数据源
 *     Attendees - 与此约会关联的参与者
 *     Details - 详细说明
 *     StartTime - 约会的开始时间
 *     EndTime - 约会的结束时间
 *     IsAllDayEvent - 约会是否来自附加日历
 *     IsPrivate - 是否是私人约会
 *     Location - 约会的地点
 *     Organizer - 约会的组织者
 *     Status - 如何处理此约会(Microsoft.Phone.UserData.AppointmentStatus 枚举)
 *         Free - 空闲
 *         Tentative - 待定
 *         Busy - 忙碌
 *         OutOfOffice - 外出
 *     Subject - 约会的主题
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

using Microsoft.Phone.UserData;

namespace Demo.ContactsAndCalendar
{
    public partial class CalendarDemo : PhoneApplicationPage
    {
        public CalendarDemo()
        {
            InitializeComponent();
        }

        private void btnGetData_Click(object sender, RoutedEventArgs e)
        {
            // 实例化 Appointments,并注册相关事件
            Appointments appointments = new Appointments();
            appointments.SearchCompleted += new EventHandler<AppointmentsSearchEventArgs>(appointments_SearchCompleted);

            DateTime start = DateTime.Now;
            DateTime end = start.AddDays(7);
            int max = 20;

            // 指定搜索范围,开始异步搜索日历数据
            appointments.SearchAsync(start, end, max, null);

            lblMsg.Text = "数据加载中,请稍后。。。";
            btnGetData.IsEnabled = false;
        }

        void appointments_SearchCompleted(object sender, AppointmentsSearchEventArgs e)
        {
            try
            {
                // 绑定所有日历的数据
                listBoxCalendar.DataContext = e.Results;

                // 只绑定主日历数据,其他附加日历的数据都过滤掉
                var primaryCalendar = from Appointment a in e.Results
                                        where a.IsAllDayEvent == false
                                        select a;
                listBoxCalendarPrimary.DataContext = primaryCalendar;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

            this.Dispatcher.BeginInvoke(delegate
            {
                btnGetData.IsEnabled = true;
                lblMsg.Text = "数据加载完毕";
            });
        }
    }
}



OK
[源码下载]

posted @ 2012-08-29 08:10  webabcd  阅读(2923)  评论(2编辑  收藏  举报