WP7 時代,API 對通訊錄只有唯讀權限,應用無法直接新增聯絡人,只能靠 Exchange、Save Contact Task 這類途徑繞一圈,對通訊錄類應用的用戶體驗限制很大。WP8 的 SDK 解除了這個限制,支援 API 級別的增刪改查,以下逐一說明。
升級到 WP8 必你如果知道的 13 個特性系列目錄:https://www.linuxidc.com/Linux/2013-08/89003.htm
寫程式前別忘了在 WMAppManifest 中聲明 ID_CAP_CONTACTS 能力。
SDK 8.0 用 ContactStore 作為聯絡人操作的入口:
ContactStore store = await ContactStore.CreateOrOpenAsync(
ContactStoreSystemAccessMode.ReadWrite,
ContactStoreApplicationAccessMode.ReadOnly);
CreateOrOpenAsync 的兩個參數都是枚舉,相當關鍵:前者宣告這個應用建立的聯絡人在 People Hub 中是否允許被使用者編輯(ReadOnly 為唯讀,ReadWrite 可讀寫);後者宣告其他應用程式能存取的範圍——LimitedReadOnly 只能看到描述資訊與縮圖,ReadOnly 則可讀取全部欄位。
async public void AddContact()
{
ContactStore store = await ContactStore.CreateOrOpenAsync(
ContactStoreSystemAccessMode.ReadWrite,
ContactStoreApplicationAccessMode.ReadOnly);
StoredContact contact = new StoredContact(store);
// contact.Id 是唯讀屬性,儲存成功後由系統自動分配
contact.GivenName = txtGivenName.Text;
contact.FamilyName = txtFamilyName.Text;
IDictionary<string, object> props = await contact.GetPropertiesAsync();
props.Add(KnownContactProperties.Email, txtMail.Text);
props.Add(KnownContactProperties.Telephone, txtPhone.Text);
await contact.SaveAsync();
MessageBox.Show("save done");
}
補充一下 RemoteId:它是聯絡人的外部識別碼,可以是 GUID,與伺服器同步時可用來做 mapping,也能直接以它反查聯絡人。
async private void UpdateContact(string remoteId, string givenName, string familyName,
string email, string codeName)
{
ContactStore store = await ContactStore.CreateOrOpenAsync();
StoredContact contact = await store.FindContactByRemoteIdAsync(remoteId);
if (contact != null)
{
contact.GivenName = givenName;
contact.FamilyName = familyName;
IDictionary<string, object> props = await contact.GetPropertiesAsync();
props[KnownContactProperties.Email] = email;
IDictionary<string, object> extprops = await contact.GetExtendedPropertiesAsync();
extprops["Codename"] = codeName;
await contact.SaveAsync();
}
}
流程與新增幾乎一樣,差別只在先用 RemoteId 或 Id 找到目標聯絡人,改完欄位再 SaveAsync。自訂欄位則透過 GetExtendedPropertiesAsync() 存取。
ContactQueryResult result = store.CreateContactQuery(); IReadOnlyList<StoredContact> contacts = await result.GetContactsAsync(); List<StoredContact> listSC = contacts.ToList(); await store.DeleteContactAsync(listSC[0].Id);
刪除最簡單,只要有 StoredContact 的 Id 就能動手。實務上建議先確認 Id 來源,避免誤刪使用者資料。