我在Windows Phone上使用LongListSelector,遇到了问题。我在此列表中的每一行都有一个复选框。
如果用户选中了我要发送到服务器的复选框,则该复选框已选中。如果用户再次取消选中该复选框,则该复选框将发送到服务器并存储为未选中状态。
当用户再次加载 View 时,将从服务器重新填充所有行,并选中相应的复选框。
我不确定如何执行此操作。我正在使用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);
}
}
有什么建议?
最佳答案
您可以为该设置添加单独的方法/ setter 。这将由负责从服务器设置初始值的代码专用。
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();
}
}
关于c# - 当使用MVVM + WP7 + LongListSelector选中对号时,如何调用服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21634791/