0
这是我第一个基于Visual Studio提供的默认模板的第一个Windows8应用程序。问题是当我尝试通过在LoadData()中创建Observable集合的新实例来分配Items属性值时,数据没有绑定,但是当我使用Items.Add方法将项添加到列表中时,我可以在UI中看到数据。我希望有些人可以解释我的行为,如果我错过了任何非常明显的事情。基于MVVM的Windows Phone 8应用程序绑定中的问题
namespace Sample.ViewModels
{
public class MainViewModel : INotifyPropertyChanged
{
public MainViewModel()
{
this.Items = new ObservableCollection<ItemViewModel>();
}
/// <summary>
/// A collection for ItemViewModel objects.
/// </summary>
public ObservableCollection<ItemViewModel> Items { get; private set; }
private string _sampleProperty = "Sample Runtime Property Value";
/// <summary>
/// Sample ViewModel property; this property is used in the view
/// to display its value using a Binding
/// </summary>
/// <returns></returns>
public string SampleProperty
{
get
{
return _sampleProperty;
}
set
{
if (value != _sampleProperty)
{
_sampleProperty = value;
NotifyPropertyChanged("SampleProperty");
}
}
}
/// <summary>
/// Sample property that returns a localized string
/// </summary>
public string LocalizedSampleProperty
{
get
{
return AppResources.SampleProperty;
}
}
public bool IsDataLoaded
{
get;
private set;
}
/// <summary>
/// Creates and adds a few ItemViewModel objects into the Items collection.
/// </summary>
public void LoadData()
{
try
{
using (IQContext context = new IQContext("isostore:/Test.sdf"))
{
var query = (from c in context.Categories
select new ItemViewModel
{
CategoryId = c.CategoryId,
CategoryName = c.CategoryName
});
// Items present in the list.
this.Items =
new ObservableCollection<ItemViewModel>(query);
// this.Items.Add(new ItemViewModel()
// { CategoryId = 1, CategoryName = "Rishi"}); // This Works
this.IsDataLoaded = true;
}
}
catch (Exception ex)
{
throw ex;
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
感谢..理解。 – Rishikesh 2013-05-03 17:39:00
要澄清:ObservableCollection有一个事件,CollectionChanged,其中一些标准视图(ListBox,LongListSelector等)订阅,以便他们可以执行增量更新。当您更改引用时,订阅侦听器无法知道这一点 - 因此您必须先NotifyProperyChanged(之后视图将放弃旧的CollectionChanged侦听器,并为新集合添加一个侦听器。) – pantaloons 2013-05-03 21:00:50