c# - 带有 INotifyPropertyChanged 实现的奇怪 NullReferenceException

标签 c# .net mvvm nullreferenceexception inotifypropertychanged

<分区>

我在基类中实现 INotifyPropertyChanged,如下所示:

public class NotifyPropertyChangedBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void RaisePropertyChanged(string propertyName)
    {
        var propChangedHandler = PropertyChanged;

        if (propChangedHandler != null)
        {
            var args = new PropertyChangedEventArgs(propertyName);
            propChangedHandler(this, args);
        }
    }
}

我是这样使用它的:

RaisePropertyChanged("Name");

当参数“this”和处理程序不为空时,我收到 NullReferenceException。任何人都可以阐明这一点吗?

谢谢。

-> 异常的完整堆栈跟踪:http://pastebin.com/bH9FeurJ

UPDATE 当我覆盖包含此属性的类的实例时发生异常。简化示例:

public class Person : INotifyPropertyChanged
{
    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            RaisePropertyChanged("Name");
        }
    }

// More properties etc.
}

-剪辑-

public class ViewModel
{
    private Person _dummyPerson;
    public Person DummyPerson
    {
        get { return _dummyPerson; }
        set
        {
            _dummyPerson = value;
            RaisePropertyChanged("DummyPerson");
        }
    }

    public void Foo()
    {
        DummyPerson = new DummyPerson(); 
        // this line throws the NRE, strangly enough the very FIRST time it works fine
    }
}

-剪辑-

我正在使用此 DummyPerson 及其 Name 属性将数据绑定(bind)到 UI。此后的第二次和所有后续尝试都会导致 NullReferenceException

最佳答案

异常不是在您的示例代码中引发的,而是在订阅的事件处理程序之一中引发的。在调试器中一步步完成,或者在Visual Studio的“调试”-“异常”菜单中打开“通用语言运行时异常”的“抛出”开关。然后你就能找出原因。

关于c# - 带有 INotifyPropertyChanged 实现的奇怪 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8476018/

相关文章:

c# - 使用反射在我的 ViewModel 中创建通用类型命令有什么缺点?

android - 使用 MVVM 模式显示和隐藏进度条

c# - ObservableCollection从一种方法而不是另一种方法更新

.net - 如何创建共享方法的扩展

c# - 从 C# 程序调用 C DLL

.net - 并行运行 ASP.Net MVC 2 和 MVC 4 的要求

c# - 在 VS 2010 中将控制台应用程序转换为 WPF 应用程序时遇到问题

c# - 如何在 WPF 上使用 IDataErrorInfo 的异常消息

c# - 我需要在 C# 中编写一个大端单精度 float 到文件

c# - 来自数据库的 MVC 5 中的动态货币