【发布时间】:2013-12-30 05:53:19
【问题描述】:
我目前正在编写一个使用 MVVM 的 Windows 8.1 应用程序。我一直远离模型只是因为当绑定到视图的数据发生更改时,我永远无法正确更新视图。没有多少网站或教程能够解释如何正确使用 INotifyPropertyChanged,我现在只是迷路了。我有以下类(包括添加该类型项目的方法)。
public class Organization
{
public Guid Id { get; set; }
public bool IsShared { get; set; }
public string Name { get; set; }
public ObservableCollection<Event> Events { get; set; }
public async static void Add(string Name)
{
Guid Id = Guid.NewGuid();
string FileName = Id.ToString() + ".txt";
var Folder = ApplicationData.Current.LocalFolder;
try
{
var Organizations = await Folder.CreateFolderAsync("Organizations", CreationCollisionOption.FailIfExists);
StorageFile File = await Organizations.CreateFileAsync(FileName, CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(File, JsonConvert.SerializeObject(new Organization { Id = Id, Name = Name, Events=new ObservableCollection<Event>() }));
}
catch
{
}
}
}
以下是我的 ViewModel:
public class OrganizationsViewModel : Base
{
private ObservableCollection<Organization> _List = new ObservableCollection<Organization>();
public ObservableCollection<Organization> List
{
get
{
Retrieve();
return _List;
}
set
{
}
}
public async void Retrieve()
{
var Folder = ApplicationData.Current.LocalFolder;
try
{
StorageFolder Organizations = await Folder.GetFolderAsync("Organizations");
var List = await Organizations.GetFilesAsync();
foreach (StorageFile i in List)
{
try
{
using (Stream s = await i.OpenStreamForReadAsync())
{
using (StreamReader sr = new StreamReader(s))
{
var item = JsonConvert.DeserializeObject<Organization>(await sr.ReadToEndAsync());
_List.Add(item);
}
}
}
catch
{
}
}
}
catch
{
}
}
}
基础存在:
public class Base : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
// property changed
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
在我的 ViewModel 和/或我的类定义中需要哪些代码,以便在我的 ObservableCollection 添加或删除项目时正确更新视图,更重要的是,为什么给定的代码可以工作?提前致谢!
【问题讨论】:
标签: c# xaml windows-runtime inotifypropertychanged