【问题标题】:application hungs up when INotifyPropertyChanged event calls当 INotifyPropertyChanged 事件调用时应用程序挂起
【发布时间】:2012-03-01 22:04:34
【问题描述】:

我的 WPF 应用程序中有一些奇怪的问题。 我正在使用 MVVM 模式,这是我的 MainWindowViewModel 的一部分:

// GridView control in MainWindow.xaml binded to this property 
public DataTable DT
{
   get { return _dt; }
}

// INotifyPropertyChanged Member for refreshing bindings
public void OnPropertyChanged(string propertyName)
{
   if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

// my function
void OnCreateTable()
{
   _dt = // creating new table here
    OnPropertyChanged("DT"); // refresh binding
}

当我调用 OnCreateTable() 程序时,几乎总是以 100% 的 CPU 使用率挂起(有时没有 CPU 使用率,但其他错误,如 GridView 控件中的错误数据)。

在调试时我发现了一些事实:

1) 如果在 OnPropertyChanged 之前暂停,则 OnCreateTable() 和数据绑定工作正常:

void OnCreateTable()
{
   _dt = // creating new table here
   Thread.Sleep(1000); //!!!
   OnPropertyChanged("DT"); // refresh binding
}

2) OnCreateTable() 和数据绑定可以正常工作,如果使用“step over”跟踪它(因为这也会在 OnPropertyChanged 之前暂停)

我不明白为什么我需要在 OnPropertyChanged 之前暂停。

【问题讨论】:

  • 你有任何线程吗?
  • 不,我没有。它的应用程序很简单。
  • 您的数据表中有多少行?如果您直接设置 itemssource 而不绑定会发生什么(仅用于测试)

标签: wpf data-binding mvvm inotifypropertychanged


【解决方案1】:

尝试设置公共属性。这是一种范围,但评论太多了。

public DataTable DT
{
    get { return _dt; }
    set 
    {
        if(_dt == value) return;
        _dt = value;
        OnPropertyChanged("DT");
    }
}

DT = // creating new table here

【讨论】:

  • 我一开始就是这样制作的。但也有同样的结果。然后我认为属性设置器中的 callint OnPropertyChanged 会导致我的问题,并在我的第一篇文章中提出。
【解决方案2】:

我想我找到了问题所在。对不起,我忘了我已经添加了属性名称检查:

public void OnPropertyChanged(string propertyName)
{
   VerifyPropertyName(propertyName);

   if (PropertyChanged != null)
         PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

[Conditional("DEBUG")]
    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)
        {
            throw new Exception("Invalid property!");
        }
    }

我不明白为什么,但调用 VerifyPropertyName() 需要暂停,否则会导致该错误,我写道。 如果我删除对 VerifyPropertyName() 的调用,一切正常!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-02
    • 2012-09-12
    • 2012-05-13
    • 2015-04-11
    • 2014-07-12
    • 2012-08-15
    • 2014-01-14
    • 1970-01-01
    相关资源
    最近更新 更多