我试图理解MVVM模式。我正在关注教程here。我在示例4框架中存货。至少对于可观察的类来说,将代码放在我身上会引起问题。我在项目中创建了一个名为HelperClass的新文件夹,并复制并粘贴了可观察的类。
Observable.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq.Expressions;
namespace Morza.HelperClass
{
[Serializable]
public abstract class ObservableObject : INotifyPropertyChanged
{
[field: NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
var handler = this.PropertyChanged;
if (handler != null)
{
handler(this, e);
}
}
protected void RaisePropertyChanged<T>(Expression<Func<T>> propertyExpresssion)
{
var propertyName = PropertySupport.ExtractPropertyName(propertyExpresssion);
this.RaisePropertyChanged(propertyName);
}
protected void RaisePropertyChanged(String propertyName)
{
VerifyPropertyName(propertyName);
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
/// <summary>
/// Warns the developer if this Object does not have a public property with
/// the specified name. This method does not exist in a Release build.
/// </summary>
[Conditional("DEBUG")]
[DebuggerStepThrough]
public void VerifyPropertyName(String propertyName)
{
// verify that the property name matches a real,
// public, instance property on this Object.
if (TypeDescriptor.GetProperties(this)[propertyName] == null)
{
Debug.Fail("Invalid property name: " + propertyName);
}
}
}
}
然而,PropertySupport表示它在当前概念中不存在。 Morza是项目名称。
我的第二个问题:
如果我想实现observable,我是否需要实现两个ViewModel,其中
如果我有一个人,我会做以下
Model
Person
ViewModel
PersonViewModel
PersonListViewModel
PersonListViewModel在哪里有一个可观察的PersonViewModel列表?
答案 0 :(得分:1)
PropertySupport
不是.NET的一部分。如果您使用的是框架教程,请确保在项目中包含该框架。
标准的INotifyPropertyChanged实现如下所示:
public event PropertyChangedEventHandler PropertyChanged;
// This method is called by the Set accessor of each property.
// The CallerMemberName attribute that is applied to the optional propertyName
// parameter causes the property name of the caller to be substituted as an argument.
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
来自MSDN。
要回答第二个问题,您的整个视图应该有一个视图模型。然后,该视图模型将包含Person
个对象的列表。如果要创建单独的Person
模型并查看模型对象,则它将包含PersonViewModel
集合。然而,这种分离通常是不必要的。
PersonListViewModel
不太可能需要。只是名字,它听起来像你不想要的课。