这是我的第一个windows8应用程序,它非常基于Visual Studio提供的默认模板。问题是当我尝试通过在LoadData()中创建Observable集合的新实例来分配Items属性值时数据没有绑定,但是当我使用Items.Add方法将项添加到列表时,我可以在UI中看到数据。我希望有人可以解释我的行为,如果我错过任何非常明显的事情。
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));
}
}
}
}
答案 0 :(得分:1)
您的Items
属性应该实现INPC,因为您要更改LoadData
中的引用,并且需要通知UI:
public ObservableCollection<ItemViewModel> Items { get; private set; }
到
private ObservableCollection<ItemViewModel> items;
public ObservableCollection<ItemViewModel> Items
{
get
{
return this.items;
}
private set
{
this.items = value;
NotifyPropertyChanged("Items");
}
}