2

I've implemented the INotifyPropertyChanged interface for a simple WPF view-viewmodel and when I call my

protected void RaisePropertyChanged(string propertyName)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

on GoodText's set like

this.RaisePropertyChanged("GoodText");

the PropertyChanged event has a method that I never assigned to it.

When it has been assigned? Who did it?

EDIT:

Thank you, great advices, but I think Willem's answer is what i was searching for, i mean: when I say

<Button Content="Button" Command="{Binding CheckButtonCommand}" />

It's something like (ugly pseudocode)

PropertyChanged += Button.GiveMeThePropertyValue;

? So the binding added the handler to the PropertyChanged event?

4

2 回答 2

1

最有可能的是,属性(以及类)是 XAML 中(或通过代码)绑定的数据。

如果绑定到实现 INotifyPropertyChanged 的​​类,则绑定到源类的 UIElement 将连接一个事件处理程序,以便能够监视属性更改。

于 2013-05-20T13:33:02.067 回答
1

这就是“类场事件”的魔力和代表的魔力。

首先是类似字段的事件:对于外部调用者来说,它们看起来像event- with add/remove访问器;它们只能与+=/一起使用-=。但是,对于声明类型,它们看起来更像是一个字段- 因此您可以直接访问委托。包括读取和赋值。

至于方法从何而来。那就是(有点)代表是什么。那实际上是.Invoke(...)在委托实例上;但这.Invoke是隐含的。任何代表都会发生这种情况,例如:

Action<string> action = s => Console.WriteLine(s);
// following are identical (but with different values, obviously)
action("hello");
action.Invoke("world");

不过有几点建议:

1:目前有一个非常小的难以咬你的线程竞赛;我建议:

var handler = PropertyChanged;
if(handler != null) handler(this, ...);

2:使用最近的编译器,您可以避免文字:

protected void RaisePropertyChanged([CallerMemberName] string propertyName=null)
{
    var handler = PropertyChanged;
    if (handler != null)
    {
        handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

它允许您从GoodText属性中调用它,如下所示:

this.RaisePropertyChanged();

更少的代码 = 更少的出错(复制/粘贴名称等)

于 2013-05-20T13:29:00.453 回答