[英]WP8 Auto-Update not working on Binding
我有一个WP8 Pivot应用程序,其中将数据绑定到XAML:
<phone:LongListSelector Grid.Row="1" Name="llsLocations" ItemsSource="{Binding}" SelectionChanged="LongListSelector_OnSelectionChanged">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<Grid Margin="0,0,0,17">
<Image Source="{Binding Icon}" HorizontalAlignment="Left" Height="54" Width="69" />
<TextBlock Text="{Binding Location}" HorizontalAlignment="Left" Margin="80,0,0,0" />
....
....
在后面的代码中,我像这样分配DataContext:
public MainPage()
{
InitializeComponent();
DataContext = App.ViewModel.Signs;
}
ViewModel.Signs对象如下所示:
public ObservableCollection<SignsViewModel> Signs { get; set; }
public MainViewModel()
{
Signs = new ObservableCollection<SignsViewModel>();
}
在SignsViewModel
对象中,我有一个NotifyPropertyChanged
,从理论上讲,只要属性更改,就应该更新UI:
private int _id;
public int ID
{
get { return _id; }
set
{
if (value != _id)
{
_id = value;
NotifyPropertyChanged("ID");
}
}
}
我有一个填充Signs
对象的Web服务:
private void GetSigns_Completed(object sender, OpenReadCompletedEventArgs e)
{
using (var sr = new StreamReader(e.Result))
{
var data = sr.ReadToEnd();
var results = JsonConvert.DeserializeObject<GetSignsResponse>(data);
App.ViewModel.Signs = results.Signs; // <--- This updates the Model
App.ViewModel.IsDataLoaded = true;
App.ViewModel.IsWaitingForData = false;
var storage = new DataStorage();
storage.SaveSigns(results.Signs);
}
}
问题是,当我调用服务并更新App.ViewModel.Signs
时,用户界面似乎并未更新。 我究竟做错了什么?
我看到的主要错误是此行,特别是在您评论“此更新模型”的地方:
var results = JsonConvert.DeserializeObject<GetSignsResponse>(data);
App.ViewModel.Signs = results.Signs; // <--- This updates the Model
App.ViewModel.IsDataLoaded = true;
最有可能发生的事情是,您破坏了ViewModel.Signs
对先前ObservableCollection
的引用。
在MainViewModel
构造函数中,您已经将Signs
属性设置为new ObservableCollection<SignsViewModel>()
。 但是,在上面的行中,您将该引用替换为results.Signs
。
我要确定的是这是否是问题,而不是
App.ViewModel.Signs = results.Signs; // <--- This updates the Model
替换为
foreach (var sign in results.Signs) {
App.ViewModel.Signs.Add(sign);
}
您应该考虑的其他事项:
您的SignsViewModel
不需要实现INotifyPropertyChanged
(我假设您已经实现),除非您希望传播对ID
属性的更新更改,即您希望用户能够Edit
ID
值。 如果只显示它们以供查看,则无需实现INotifyPropertyChanged
。
我不建议将整个Page的DataContext
设置为除最外面的ViewModel以外的任何内容。 而不是
DataContext = App.ViewModel.Signs;
我会选
DataContext = App.ViewModel;
然后有一个
<phone:LongListSelector Grid.Row="1" Name="llsLocations" ItemsSource="{Binding Signs}" SelectionChanged="LongListSelector_OnSelectionChanged">
如果您打算拥有更多功能,那就更好了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.