2

我想创建一个 ViewModel 类来从数据库中检索值。我的目标是从我的数据库表中检索 RAM 的使用值(RAM 总数和可用的 RAM),然后将其显示在我的视图中。

这就是我迄今为止在我的 ViewModel 类上所做的

public class RamViewModel : INotifyPropertyChanged
{
    float _ramTotal;
    float _ramUsed;

    public float RamTotal
    {
        get { return _ramTotal; }
        set { _ramTotal = value; RaisePropertyChanged("RamTotal"); }
    }

    public float RamUsed
    {
        get { return _ramUsed; }
        set { _ramUsed = value; RaisePropertyChanged("RamUsed"); }
    }

    private void RaisePropertyChanged(string p)
    {
        throw new NotImplementedException();
    }
  }

当我构建这个类时,我得到了这个错误,“ViewModel.RamViewModel 没有实现接口成员'System.ComponentModel.INotifyPropertyChanged.PropertyChanged'”

如何克服这个错误

4

2 回答 2

2

您的类不会公开PropertyChanged事件,这对于实现的类是必需的INotifyPropertyChanged(它是该接口的唯一成员)。

所以你应该添加:

public event PropertyChangedEventHandler PropertyChanged;

private void RaisePropertyChanged(string propertyName)
{
    var handler = this.PropertyChanged;
    if (handler != null) {
        handler(this, new PropertyChangedEventArgs(propertyName);
    }
}

ObservableCollection与此无关。

于 2013-01-08T18:37:52.140 回答
2

INotifyPropertyChanged 是一个接口,其中一个成员需要包含在您的类定义中:

    public event PropertyChangedEventHandler PropertyChanged;

You should also change the code in RaisePropertyChanged to not throw an exception, by implementing the actual functionality:

    private void RaisePropertyChanged(string p)
    {
        if (null != PropertyChanged) PropertyChanged(this, new PropertyChangedEventArgs(p));
    }
于 2013-01-08T18:38:40.627 回答