[英]How to Call Server when Checkmark is hit using MVVM + WP7 + LongListSelector
我在Windows Phone上使用LongListSelector,遇到了問題。 我在此列表中的每一行都有一個復選框。
如果用戶選中了我要發送到服務器的復選框,則該復選框已選中。 如果用戶再次取消選中該復選框,則該復選框將發送到服務器並存儲為未選中狀態。
當用戶再次加載視圖時,將從服務器重新填充所有行,並選中相應的復選框。
我不確定如何執行此操作。 我正在使用MVVM模式,所以我在模型中具有IsChecked屬性(列表中每一行的模型都具有一個)。
起初,我以為我可以在IsChecked屬性中調用服務器,但是如果這樣做,那么每次初始加載都將調用服務器。
/// <summary>
/// The <see cref="IsChecked" /> property's name.
/// </summary>
public const string IsCheckedPropertyName = "IsChecked";
private bool isChecked = false;
/// <summary>
/// Sets and gets the IsChecked property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public bool IsChecked
{
get
{
return isChecked;
}
set
{
if (isChecked == value)
{
return;
}
// if I do this here then it will solve my problem when a user checks a box but when I do initial load I will face the problem
// that it will call my server for every row for no reason at all.
CallWebService(value);
RaisePropertyChanging(() => IsChecked);
isChecked = value;
RaisePropertyChanged(() => IsChecked);
}
}
有什么建議么?
您可以為該設置添加單獨的方法/設置器。 這將由負責從服務器設置初始值的代碼專用。
public bool IsCheckedSetting
{
set
{
if (value == isChecked)
return;
isChecked = value;
RaisePropertyChanged(() => IsChecked);
}
}
上面的方法是可以的,但是如果您有很多設置,那么為每個設置創建2個屬性是一種拖累。 在這種情況下,另一種方法是圍繞服務代理創建包裝器類。 該包裝器應跟蹤每個屬性的值,並且僅在值實際上已更新時才調用遠程服務。 僅用於說明:
public class SettingsWrapper
{
Dictionary<string, object> settings = new Dictionary<string, object>();
// TODO populate with initial values from server
public bool UpdateSetting<T>(string name, T value)
{
// only update if the initial value is ready, and if the new value is different
if (settings.ContainsKey(name) && (T)settings[name] != value)
CallWebService();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.